【问题标题】:how to generate empty array in json4s?如何在json4s中生成空数组?
【发布时间】:2014-12-29 10:54:26
【问题描述】:

我有 2 位 scala 代码使用 json4s dsl 来生成 json 内容

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)

首先,我得到了我的期望:

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

但是对于空列表,我没有得到数组。相反,我得到了

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

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

注意第一种情况下的菜单是JArray(List(Jobject,第二种情况下是JObject(List()

这是设计使然吗?这目前用于测试,但我需要了解发生了什么,因为我的真实世界代码可能在许多地方都有空列表,并且接收者期待一个数组。

【问题讨论】:

    标签: arrays list scala json4s


    【解决方案1】:

    您需要将 json4s 支持的显式类型传递给 List 构造函数才能使事情正常工作,否则将推断出 Nothing

    【讨论】:

    • val feastNoMenu = "Feast" -> ("target" -> "me") ~ ("menus" -> List.empty[JInt])
    猜你喜欢
    • 2016-12-31
    • 2018-02-14
    • 2013-07-06
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 2011-03-11
    相关资源
    最近更新 更多