ed_me
ed_me

Reputation: 3508

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.

Upvotes: 0

Views: 973

Answers (2)

gustf
gustf

Reputation: 2017

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

Upvotes: 1

nyname00
nyname00

Reputation: 2566

XML.toJSONObject(...) internally calls static Object stringToValue(String string) which will always try to convert the value to Boolean, JSONObject.Null, Long and Double first, and return a String only when all conversion attempts fail. There seems to be no (easy) way around this.

Instead of forking or doing some reflection magic, you can simply convert the value when reading:

JSONObject rec = json.getJSONObject("record");
String name = rec
                .get("name")
                .toString();

// optionally put the string value back into your JSON:
rec.put("name", name);

Upvotes: 0

Related Questions