cyrilantony
cyrilantony

Reputation: 294

How to format array elements during json to xml convertion using json-lib?

The below json converted to xml using json-lib utility.

{
   "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"
         }
      ]
   }
}

Code used is :

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

The <root> tag was removed . After removal 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>

EXPECTED FORMAT:

<?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>

Is there way to tweak the xml conversion in expected xml format ?

Upvotes: 3

Views: 514

Answers (1)

Christophe
Christophe

Reputation: 2200

I found no solution using json-lib

You can get your expected result easily by using the library from json.org intead.

Here is the maven dependency if you want

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>

Here is the code that I used to get the result:

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);

Upvotes: 0

Related Questions