I want to convert an xml to json.
The format of of xml is as follows -
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);
}
...
...
While working on a group project I ran into the same issue you have described. The solution we used to get this to work was to change our Maven dependency from Jackson to json-lib. We used this site as a guide: http://answers.oreilly.com/topic/278-how-to-convert-xml-to-json-in-java/
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<type>jar</type>
<classifier>jdk15</classifier>
<scope>compile</scope>
</dependency>
--$pli7
I also ran into this issue, using Jackson 2.5. My solution was to replace the implementation of javax.json.JsonObjectBuilder
in use with my own, which when a new object is added behaves like this :
public class CustomJsonObjectBuilder implements JsonObjectBuilder {
private final Map<String, JsonValue> jsonFragments;
// other methods omitted for brevity
public JsonObjectBuilder add(String name, JsonValue value) {
if(jsonFragments.containsKey(name)) {
JsonValue oldValue = jsonFragments.get(name);
JsonArrayBuilder newBuilder = new JsonArrayBuilderImpl();
if(oldValue instanceof JsonArray) {
JsonArray theArray = (JsonArray) oldValue;
for (JsonObject oldValues : theArray.getValuesAs(JsonObject.class)) {
newBuilder.add(oldValues);
}
} else {
newBuilder.add(oldValue);
}
newBuilder.add(value);
jsonFragments.put(name, newBuilder.build());
} else {
jsonFragments.put(name, value);
}
return this;
}