如何使用json-lib在json到xml转换期间格式化数组元素?

时间:2013-05-13 10:36:19

标签: xml json json-lib

以下json使用json-lib实用程序转换为xml。

{
   "tms:getTaskListResponse": {
      "tms:task": [
         {
            "tms:creationDate": "2013-05-06T12:02:21.530+05:30",
            "tms:instanceId": "403"
         },
         {
            "tms:creationDate": "2013-05-06T12:04:50.730+05:30",
            "tms:instanceId": "1224"
         }
      ]
   }
}

使用的代码是:

XMLSerializer serializer = new XMLSerializer();
serializer.setRootName("root");
serializer.setTypeHintsEnabled(false);
JSON json = JSONSerializer.toJSON(jsonString);
String xmlResponse = serializer.write(json);

<root>标记已删除。删除后 OUTPUT XML:

<?xml version="1.0" encoding="UTF-8"?>
<tms:getTaskListResponse >
   <tms:task>
      <e>
         <tms:creationDate>2013-05-06T12:02:21.530+05:30</tms:creationDate>
         <tms:instanceId>403</tms:instanceId>
      </e>
      <e>
         <tms:creationDate>2013-05-06T12:04:50.730+05:30</tms:creationDate>
         <tms:instanceId>1224</tms:instanceId>
      </e>
   </tms:task>
</tms:getTaskListResponse>

预期格式:

<?xml version="1.0" encoding="UTF-8"?>
<tms:getTaskListResponse >
   <tms:task>
         <tms:creationDate>2013-05-06T12:02:21.530+05:30</tms:creationDate>
         <tms:instanceId>403</tms:instanceId>
   </tms:task>
   <tms:task>
         <tms:creationDate>2013-05-06T12:04:50.730+05:30</tms:creationDate>
         <tms:instanceId>1224</tms:instanceId>
   </tms:task>
</tms:getTaskListResponse>

有没有办法以预期的xml格式调整xml转换?

1 个答案:

答案 0 :(得分:0)

我找不到使用json-lib的解决方案

您可以使用json.org intead中的库轻松获得预期结果。

如果你想要

,这是maven依赖
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>

以下是我用来获得结果的代码:

import org.json.JSONObject;
import org.json.XML;

    String jsonString = "{   \"tms:getTaskListResponse\": {      \"tms:task\": [         {            \"tms:creationDate\": \"2013-05-06T12:02:21.530+05:30\",            \"tms:instanceId\": \"403\"         },         {            \"tms:creationDate\": \"2013-05-06T12:04:50.730+05:30\",            \"tms:instanceId\": \"1224\"         }      ]   }}";

    JSONObject json = new JSONObject(jsonString);
    String xmlResponse = XML.toString(json);

    System.out.println(xmlResponse);