2

I'm working in scala but a java solution is acceptable.

I've been using org.json to convert my json api into xml so a odd-ball client (VB4 based and unwilling to change) can consume my api in xml.

Simple json to xml conversion works fine. Problem is I likely need to be able to roundtrip it and org.json doesn't seem to convert back and forth properly.

eg

{
    "a" : ""
}

converts to:

<a></a>

when I convert this back I get:

{
    "a" : { }
}

So org.json converts an empty string to an empty tag, and an empty tag into an empty object. My code is below:

object XmlSerializer {
  def toXml(json:String) = {
    val jsonObj = new JSONObject(json)
    val xmlString = XML.toString(jsonObj)

    xmlString
  }

  def fromXml(xml:String) = {
    val jsonObj = XML.toJSONObject(xml)
    val jsonString = jsonObj.toString

    jsonString
  }
}

Am I missing something or is the org.json.XML conversion just not smart enough? Seems a type attribute could have been used to guarantee conversion back to the correct type.

0

1 Answer 1

1

The problem is that the JSON API assumes an empty set once it reads:

<a></a>

In the latest version of the library it actually returned <a/>. One possible workaround, (if spaces are OK in the XML) is to replace your empty values with a single space. Here is a rough example:

val INPUT_JSON = "{ \"a\" : \"\" }";
var input = INPUT_JSON.replaceAll("\"\"", "\" \"");
var jsonObj = new JSONObject(input);
var xmlString = XML.toString(jsonObj);
println("JSON to XML: " + xmlString);

var xmlJSONObj = XML.toJSONObject(xmlString);
var jsonOutputString = xmlJSONObj.toString();
println("XML back to JSON: " + jsonOutputString);

output:

JSON to XML: <a> </a>
XML back to JSON: {"a":""}
Sign up to request clarification or add additional context in comments.

1 Comment

That only works if you assume that the json { "a" : " " } will never occur. Also further annoyances { "a" : ["b"] } will convert back to { "a" : "b" } since the xml <a>b</a> is the same as if it was a single item.

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.