1

I have the following JSON structure :

{
   "userId": "55",
   "Unit": [
      {
         "id": "1",
         "unitname": "unit1",
         "eventId": "2",
         "transactiontype": "1"
      },
      {
         "id": "2",
         "unitname": "unit2",
         "eventId": "2",
         "transactiontype": "1"
      },
      {
         "id": "3",
         "unitname": "unit3",
         "eventId": "2",
         "transactiontype": "2"
      }
   ]
}

and I need to convert it to the below XMl format :

<Units userId="55">

<Unit id="1" unitname="unit1" eventId="2"  transactiontype="1"/>
<Unit id="2" unitname="unit2" eventId="2"  transactiontype="1"/>
<Unit id="3" unitname="unit3" eventId="2"  transactiontype="2"/>

</Units>

While trying it through java I ma getting an XML but it shows XML elements as below :

<UnitId>1</UnitId>

Can someone please help me as to what needs to be done so that I get the XML format needed, i.e as attributes.

1
  • There are many ways of converting JSON to XML and you need to say which one you are using, and how you are using it. Commented May 23, 2017 at 9:38

2 Answers 2

1

Maybe you can use the json.org library. I'm not sure if this library does exactly what you want.

You can use it like that:

JSONObject json = new JSONObject(str);
String xml = XML.toString(json);

toString can take a second argument to provide the name of the XML root node.

XML to JSON using XML.toJSONObject(java.lang.String)

POM

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20170516</version>
</dependency>
Sign up to request clarification or add additional context in comments.

Comments

0

Here is an XSLT 3.0 solution.

<xsl:transform version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template name="main">
  <xsl:variable name="in" select="json-doc('input.json')" as="map(*)"/>
  <Units userId="{$in?userId}">
    <xsl:for-each select="$in?Unit?*"
      <Unit id="{?id}" unitname="{?unitname}" 
            eventId="{?eventId}"  transactiontype="{?transactiontype}"/>
    </xsl:for-each>
  </Units>
</xsl:template>

</xsl:transform>

You can run this from Java by installing Saxon-PE 9.7.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.