简体   繁体   English

在Java中从xml转换为json时处理元素的单次出现

[英]handling single occurrence of element while converting from xml to json in java

I have to convert xml string to json object using java, this is very a common requirement , for which I have used below code which works very fine 我必须使用Java将xml字符串转换为json对象,这是非常常见的要求,为此我使用了下面的代码,效果很好

content = "<books>
               <science>
                 <name>volcano</name>
               </science>
               <science>
                 <name>gravity</name>
               </science>
           </books>"
JSONObject xmlJSONObj = XML.toJSONObject(content);
String jsonPrintString = xmlJSONObj.toString();
System.out.println(jsonPrintString);

output looks like: 输出看起来像:

{
"books": {
"science": [
  { "name": "volcano" },
  { "name": "gravity" }
]
}
}

now suppose my input content string is like the below one 现在假设我的输入内容字符串如下所示

<books>
   <science>
     <name>volcano</name>
   </science>
</books>

I still require output as 我仍然需要输出

{
 "books": {
 "science" : [
    { "name" : "volcano" }
  ]
 }
 }

where the element science is still represented as list , as I need to feed this json as input to a tool which needs the element science as a list else if output is as 其中元素科学仍表示为list,因为我需要将此json作为输入提供给需要将元素科学作为列表的工具,否则输出为

{
 "books": {
  "science": { "name": "volcano" }
 }
 } 

it fails as science is not a list. 它失败了,因为科学不在清单上。 Please provide me some tips on this. 请为我提供一些提示。 Thanks in advance. 提前致谢。

This is not a Java problem, but an XML problem. 这不是Java问题,而是XML问题。 Given just the input XML data the converter cannot determine if the 'science' element is a single or multiple value. 仅给出输入XML数据,转换器就无法确定'science'元素是单个还是多个值。 The above code is not wrong. 上面的代码没有错。 It just doesn't have enough information and consequently does the wrong assumption. 它只是没有足够的信息,因此做错了假设。 What is needed is a definition of the structure of these documents. 需要的是这些文件的结构的定义。 A DTD or an XML Schema definition. DTD或XML模式定义。 Once you have such a definition you can even use more sophisticated approaches like JAXB to properly parse the XML. 一旦有了这样的定义,您甚至可以使用更复杂的方法(例如JAXB)来正确解析XML。 Serializing to JSON would then be a piece of cake. 然后,序列化为JSON将是小菜一碟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM