0

I have a query object:

case class SearchQuery(keyword: String, count: Int, sort: String)

I serialize this object to send it to a restful api to get search response. Is it possible to not write some of the properties when serializing based on some condition like, if sort is empty I want the json string to be "{keyword: 'whatever', count: 25}" and if sort is non empty then I would like it to be "{keyword: 'whatever', count: 25, sort: 'unitPrice'}". What is best way to achieve this?

I am using lift json for serialization.

Any help is greatly appreciated. Thank you.

Update

val reqHeaders: scala.collection.immutable.Seq[HttpHeader] = scala.collection.immutable.Seq(
      RawHeader("accept", "application/json"),
      RawHeader("authorization", "sgdg545wf34rergt34tg"),
      RawHeader("content-type", "application/json"),
      RawHeader("x-customer-id", "45645"),
      RawHeader("x-locale-currency", "usd"),
      RawHeader("x-locale-language", "en"),
      RawHeader("x-locale-shiptocountry", "US"),
      RawHeader("x-locale-site", "us"),
      RawHeader("x-partner-id", "45sfg45fgd5")
    )

implicit val formats = DefaultFormats
val searchObject = net.liftweb.json.Serialization.write(req) //req is search object
val searchObjectEntity = HttpEntity(ContentTypes.`application/json`, searchObject)
val request = HttpRequest(HttpMethods.POST, "https://api.xxxxxxx.com/services/xxxxxxxx/v1/search?client_id=654685", reqHeaders, searchObjectEntity)
An Illusion
  • 769
  • 1
  • 10
  • 24

2 Answers2

1

In Lift-Json, optional values are not serialized. So if you change your case class to have case class SearchQuery(keyword: String, count: Int, sort: Option[String]), you should get just the behavior you want.

See "Any value can be optional" in

https://github.com/lift/lift/tree/master/framework/lift-base/lift-json

radumanolescu
  • 4,059
  • 2
  • 31
  • 44
0

You can make your your sort field optional, as scala gives you a way of handling fields which can be optional and then use Lift Json or Jerkson Json for serialization.

Here is the sample code with Jerkson Json.

case class SearchQuery(keyword: String, count: Int, sort: Option[String])
com.codahale.jerkson.Json.generate(SearchQuery("keyword",1,None))

This will give you output ->

{"keyword":"keyword","count":1}
geek94
  • 443
  • 2
  • 11