将XML转换为具有Lift的Json的行为很奇怪 [英] converting xml to Json with lift behaves strange
问题描述
我正在为scala API使用scala/lift.在后台,我正在生成xml,它将通过Xml.toJson()作为输出转换为json.
I'm using scala / lift for a Rest API. Under the hood I'm generating xml which will be converted to json via Xml.toJson() as output.
现在,我注意到一些奇怪的行为使我发疯.
Now i noticed some strange behavior which drives me nuts.
例如,我有以下xml:
for example i have the following xml:
<data>
<item>
<foo>1</foo>
<bar>1</bar>
</item>
<item>
<foo>2</foo>
<bar>2</bar>
</item>
</data>
xml.toJson()的结果如下:
the result of xml.toJson() looks like:
JObject(
List(
JField(
data,JObject(
List(
JField(item,
JArray(
List(
JObject(
List(
JField(foo,JString(1)),
JField(bar,JString(1)))
),
JObject(
List(
JField(foo,JString(2)),
JField(bar,JString(2))
)
)
)
)
)
)
)
)
)
)
但是如果我添加一个新的xml元素:
but if i add a new xml element:
<data>
<baz>234</baz>
<item>
<foo>1</foo>
<bar>1</bar>
</item>
<item>
<foo>2</foo>
<bar>2</bar>
</item>
</data>
关于JArray的结果是不同的:
the result is different regarding the JArray:
JObject(
List(
JField(data,JObject(
List(
JField(baz,JString(234)),
JField(item,JObject(
List(
JField(foo,JString(1)),
JField(bar,JString(1))
))
),
JField(item,JObject(
List(
JField(foo,JString(2)),
JField(bar,JString(2))
))
)
)
))
)
)
未定义数组,我有两个名称为"item"的对象.这是正常现象吗?我希望数组不包裹"item"标签周围的东西.
The array isn't defined and i have two objects with the name "item". Is this a normal behavior? I would like to have the array without wrapping someting aroung the "item" Tags.
推荐答案
是的,这是预期的行为:如果所有子元素都具有相同的名称,则net.liftweb.json.Xml
仅将子元素分组为JArray
.您可以尝试通过处理生成的JSON来解决此问题:
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:
- 我们正在使用
groupBy
,因此我们可能最终会重新排列 子元素. - 如果只有一个
item
,它将不会被包裹在JArray
中.
- We're using
groupBy
, so we may end up rearranging the order of child elements. - If there's only one
item
, it won't get wrapped in aJArray
.
根据您的关心程度,您可以针对这些问题写出自己的方式,但是几乎可以肯定这是不值得的.只需忽略net.liftweb.json.Xml
并从Scala数据结构生成XML和JSON.
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.
这篇关于将XML转换为具有Lift的Json的行为很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!