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)
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