Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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]'");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top