Search code examples
javajsonxmlorg.json

XML to JSON producing undesired results


I'm using the org.json library, as seen below, to convert from XML to JSON

  <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20160212</version>
  </dependency>

A simple test case shows the problem I am having, see below: -

I have the following XML

<record>
  <name>A108B</name>
</record>

which in turn, produces

{"record": { "id": "A108B" }}

Great! The problem occurs if id is 1111

Using the following code

XML.toJSONObject(xml...)

I get

{"record": { "name": 1111 }}

I'd actually prefer to keep the values as all strings, i.e. user identifiers. I don't want the output changing depending on whether the identifier happens to not have a character in it.

Is there any way I can force org.json to do this? I can probably fork the code and make a change for myself but I would expect that this is a problem someone else has come across and has a solution for.


Solution

  • This seems to do the trick, I had to override the nextValue of JSONTokener.

        String xml = "<test>111</test>";
        JSONObject json = XML.toJSONObject(xml);
        JSONTokener tokener = new JSONTokener(json.toString()) {
            public Object nextValue() throws JSONException {
                Object nextValue = super.nextValue();
                if (nextValue instanceof Number) {
                    Number value = (Number) nextValue;
                    return value.toString();
                }
                return nextValue;
            }
        };
        json = new JSONObject(tokener);
        System.out.println(json.toString());
    

    Output: {"test":"111"}