What are some good tools for quickly and easily converting XML to JSON in Java?
Thanks in advance for all your help!
What are some good tools for quickly and easily converting XML to JSON in Java?
Thanks in advance for all your help!
The JSON in Java page on json.org has some great resources.
Looks like XML.java and JSONML.java are the classes you're looking for:
public class Main {
public static int PRETTY_PRINT_INDENT_FACTOR = 4;
public static String TEST_XML_STRING =
"<?xml version=\"1.0\" ?><test attrib=\"moretest\">Turn this to JSON</test>";
public static void main(String[] args) {
try {
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
} catch (JSONException je) {
System.out.println(je.toString());
}
}
}
Looks like it does the job. Output is:
{"test": {
"attrib": "moretest",
"content": "Turn this to JSON"
}}
Expanded from my original entry. I hope this helps.
I don't know what you exact problem is, but if your receiving XML and want to return JSon (or something) you could also look at JAX-B. This is a standard for marshalling/unmarshalling Java POJO's to XML and/or Json. There are multiple libraries that implement JAX-B, for example Apache's CXF.