0

I have a requirement where the tags of the XML will be dynamic for different files. For example:

XML File 1:

<?xml version="1.0" encoding="utf-8"?>
 <Order>
      <DueDate>12/25/2020</DueDate>
      <CreatedBy>User1</CreatedBy>
      <OrderType>Print</OrderType>
      <ReferenceNumber>A1234</ReferenceNumber>
 </Order>

XML File 2:

 <?xml version="1.0" encoding="utf-8"?>
 <Job>
      <LastDate>12/25/2020</LastDate>
      <CreatedUser>User1</CreatedUser>
      <JobType>Print</JobType>
      <TrackingNumber>A1234</TrackingNumber>
 </Job>

I want to convert to JSON as below. The JSON structure will not be varying.

{
   "dueDate" : "12/25/2020",
   "createdBy": "User1",
   "jobType" : "Print",
   "trackingNumber": "A1234"
}

As different XMLs have different formatted tags, is it possible to have a mapping file per xml data somewhere on a server or on DB, where I can reference it and do the conversion? I need a mapping something similar to below:

XmlToJson1.properties:

dueDate=DueDate
createdBy=CreatedBy
orderType=OrderType
trackingNumber=ReferenceNumber 

XMLToJson2.properties

dueDate=LastDate
createdBy=CreatedUser
orderType=JobType
trackingNumber=TrackingNumber

How do I do this in Java?

Any tips would be helpful?

Note: I do not want to make changes in Java code every time a new XML format comes in.

Sriram
  • 155
  • 12
  • Maybe this helps? https://stackoverflow.com/questions/1823264/quickest-way-to-convert-xml-to-json-in-java The answer on this post is quite antique but it could help – Crude Code Dec 23 '20 at 09:24
  • HI Sebastan, The options provided in the link will be converting to a generic json format ie. for example: will get converted to "ReferenceNumber". However I need the to be converted to "trackingNumber". How to do this? – Sriram Dec 23 '20 at 09:29
  • You probably need to change the node name before you do the json conversion. It also may be a solution for you to do a xml transformation to a defined java object which you can then convert to json with jackson. Have a look at this thread: https://stackoverflow.com/questions/1299926/changing-node-name-of-xml-node-with-java I would probably do a xml transformation and do the json conversion with jackson – Crude Code Dec 23 '20 at 09:42
  • Underscore-java library has a static method U.xmlToJson(xmlString). – Valentyn Kolesnikov Jan 11 '21 at 12:54

0 Answers0