Search code examples
jsonscalalift-json

How to Conditionally Produce JSON Using JSON4S


I am using JSON4S to produce some JSON.

If a condition is met, I would like to produce the following:

{"fld1":"always", "fld2":"sometimes"}

If the condition is not met, I would like to produce:

{"fld1":"always"}

What I have tried so far is:

val fld1 = "fld1" -> "always"

val json = if(condition) ("fld2" -> "sometimes") ~ fld1 else fld1

compact(render(json))

However, this gives me a type mismatch in the render "Found: Product with Serializable. Required: org.json4s.package.JValue".

The interesting this is that render(("fld2" -> "sometimes") ~ fld1) works, and so does render(fld1). The problem seems to be with the type inferred for json.

How could I fix this?


Solution

  • Not the nicest way I can think of, but declaring the type yourself should work:

    val json: JObject = 
      if(condition) ("fld2" -> "sometimes") ~ fld1 else fld1
    
    compact(render(json))
    

    Also, note that you can get type inference to help itself out: If you can render in one go:

    compact(render(
      if(condition) fld1 ~ ("fld2" -> "sometimes") else fld1  
    ))