1

I have code that looks something like this:

import net.sf.json.*;--just so you know what the library is
...
JSONArray a = new JSONArray();
JSONObject p = new JSONObject();
p.put("some_attribute1","some normal string");
p.put("some_attribute2","[3something]");
p.put("some_attribute3","[something3]");
a.add(p);
System.out.println(a.toString());

This produces:

[
    {
        "some_attribute1":"some normal string",
        "some_attribute2":["3something"],
        "some_attribute3":"[something3]"
    }
]

instead of the desired result:

[
    {
        "some_attribute1":"some normal string",
        "some_attribute2":"[3something]",
        "some_attribute3":"[something3]"
    }
]

Notice the difference between "some_attribute2" being an array in the actual output versus a string in the desired output. Can anyone explain why this is? Also if there is a term for what is going to better categorize my question?

Reimius
  • 5,694
  • 5
  • 24
  • 42

2 Answers2

0

This is actually a bug that has been reported already. Here's the link: http://sourceforge.net/tracker/?func=detail&aid=3201838&group_id=171425&atid=857928

... it doesn't look like this library is supported anymore, the issue has existed since mid 2011...

We've been put off by the json-lib library not being officially supported anymore, and decided to switch to gson. This issue can be caused by too many places in our code to not have any good fix or workaround.

Reimius
  • 5,694
  • 5
  • 24
  • 42
-1

Looks like strange behaviour but if put tries to convert the value to a JSONObject and if I interpret the documentation correctly it seems that you need to quote some strings:

Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: { } [ ] / \ : , = ; # and if they do not look like numbers and if they are not the reserved words true, false, or null.

This means you if you want a string you should use:

p.put("some_attribute2","'[3something]'");
kapex
  • 28,903
  • 6
  • 107
  • 121
  • does not work. I read that documentation and that section is for conversion from JSON encoding into the java representation. I'm going from Java to JSON in the example above. – Reimius Jan 21 '13 at 18:16
  • @Reimius The section is about 'constructors' but it doesn't fit those of JSONObject, so I think it refers to the 2nd argument of the [element(String, Object)](http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html#element%28java.lang.String,%20java.lang.Object%29) method which does Java to JSON conversion. It was just a guess that it also applies to `put` which looks like it should do the same but has no documentation. – kapex Jan 22 '13 at 10:29
  • Have you tested this? I believe that I did and it still does not work. – Reimius Jan 22 '13 at 14:29