Michael Allen
Michael Allen

Reputation: 5828

org.json.XML conversion json to xml to json fails

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.

Upvotes: 2

Views: 5692

Answers (1)

Reimeus
Reimeus

Reputation: 159754

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":""}

Upvotes: 1

Related Questions