Search code examples
arrayslistscalajson4s

how to generate empty array in json4s?


I've 2 bits of scala code using the json4s dsl to produce json content

val feastWithMenus = "Feast" ->
("target" -> "me") ~
  ("menus" -> List(
    ("first" -> "pate") ~
      ("mains" -> "beef") ~
      ("dessert" -> "ice-cream")
    ,
    ("first" -> "soup") ~
      ("mains" -> "omlette") ~
      ("dessert" -> "ice-cream")
  ))

  val feastNoMenu = "Feast" ->
("target" -> "me") ~ 
  ("menus" -> List.empty)

In the first instance, I get what I'm expecting:

{"Feast":{"target":"me","menus":[{"first":"pate","mains":"beef","dessert":"ice-cream"},     {"first":"soup","mains":"omlette","dessert":"ice-cream"}]}}

JObject(List((Feast,JObject(List((target,JString(me)), (menus,JArray(List(JObject(List((first,JString(pate)), (mains,JString(beef)), (dessert,JString(ice-cream)))), JObject(List((first,JString(soup)), (mains,JString(omlette)), (dessert,JString(ice-cream))))))))))))

but for the empty list I don't get an array. Instead I get

{"Feast":{"target":"me","menus":{}}}

JObject(List((Feast,JObject(List((target,JString(me)), (menus,JObject(List())))))))

Notice in the first case menus is a JArray(List(Jobject and in the second it's a JObject(List()

Is this by design? this is currently for testing but I need to understand what's going on as my real world code will potentially have empty lists in a number of places and recipient is expecting an array.


Solution

  • You need to pass an explicit type supported by json4s to the List constructor in order to make things work, otherwise Nothing will be inferred.