"jackson xml to json converter removes multiple child records" Code Answer

4

i was able to get the solution to this problem by using org.json api to convert source xml to jsonobject and then to json by jackson api.

code

import java.io.file;
import java.io.fileinputstream;
import java.io.inputstream;

import org.apache.commons.io.ioutils;
import org.json.jsonobject;
import org.json.xml;

import com.fasterxml.jackson.databind.objectmapper;
import com.fasterxml.jackson.databind.serializationfeature;

...
...

try (inputstream inputstream = new fileinputstream(new file(
                "source.xml"))) {
    string xml = ioutils.tostring(inputstream);
    jsonobject jobject = xml.tojsonobject(xml);
    objectmapper mapper = new objectmapper();
    mapper.enable(serializationfeature.indent_output);
    object json = mapper.readvalue(jobject.tostring(), object.class);
    string output = mapper.writevalueasstring(json);
    system.out.println(output);
}

...
...

source xml

<?xml version="1.0" encoding="iso-8859-1"?>
<file>
  <numleases>1</numleases>
  <flag>success</flag>
  <message>test upload</message>
  <lease>
     <leaseversion>1</leaseversion>
     <f1501b>
        <nedoco>18738</nedoco>
        <nwunit>0004</nwunit>
        <ntrustrecordkey>12</ntrustrecordkey>
     </f1501b>
     <f1501b>
        <nedoco>18739</nedoco>
        <nwunit>0005</nwunit>
        <ntrustrecordkey>8</ntrustrecordkey>
     </f1501b>
  </lease>
</file>

output

{
  "file" : {
    "numleases" : "1",
    "flag" : "success",
    "message" : "test upload",
    "lease" : {
      "leaseversion" : "1",
      "f1501b" : [ {
        "nedoco" : "18738",
        "nwunit" : "0004",
        "ntrustrecordkey" : "12"
      }, {
        "nedoco" : "18739",
        "nwunit" : "0005",
        "ntrustrecordkey" : "8"
      } ]
    }
  }
}
By Suic on October 6 2022

Answers related to “jackson xml to json converter removes multiple child records”

Only authorized users can answer the Search term. Please sign in first, or register a free account.