converting xml to Json with lift behaves strange

喜欢而已 提交于 2019-12-05 12:31:16

Yep, this is the intended behavior: net.liftweb.json.Xml will only group child elements into a JArray if they all have the same name. You can try to get around this behavior by manipulating the generated JSON:

JObject(
  (json \ "data").asInstanceOf[JObject].obj.groupBy(_.name).map {
    case (_, v :: Nil) => v
    case (k, vs)       => JField(k, JArray(vs.map(_.value)))
  }.toList
)

But there are at least a couple of potential problems here:

  1. We're using groupBy, so we may end up rearranging the order of child elements.
  2. If there's only one item, it won't get wrapped in a JArray.

Depending on how much you care, you could write your way around these issues, but it's almost certainly not worth it. Just ignore net.liftweb.json.Xml and generate both your XML and your JSON from a Scala data structure.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!