Hi guys I’m developing a Restful + JSON servlet, but I got a strange problem, if i try to compile my project source with this method:
public
static
WipdDBTable
parseJSON(String JSONBody)
{
JSONObject jsonObj;
JSONTokener jsonTok;
Iterator it;
String[] labels;
String[][] fields;
int i;
try {
jsonTok = new JSONTokener(JSONBody);
jsonObj = new JSONObject(jsonTok);
labels = new String[jsonObj.length()];
fields = new String[1][labels.length];
i = 0;
it = jsonObj.keys();
while(it.hasNext()) {
String key = it.next().toString();
labels[i] = key;
fields[0][i] = jsonObj.get(key);
i++;
}
return new WipdDBTable(labels, fields);
} catch(JSONException ex) {
return null;
}
}
I get this error:
WipdJSON.java:102: incompatible types
found : java.lang.Object
required: java.lang.String
fields[0][i] = jsonObj.get(key);
So I wrote a test class, with apparently the same source, but with this one I don’t get any error:
public class jsontest
{
public static
void
main(String[] args)
{
String s1;
JSONObject jsonObj;
JSONTokener jsonTok;
s1 = "{\"lo\":\"ol\",\"json\":{\"1\":\"2\"},\"yo\":{\"lol\":\"lol\"}}";
try {
jsonTok = new JSONTokener(s1);
jsonObj = new JSONObject(jsonTok);
Iterator it = jsonObj.keys();
while(it.hasNext()) {
String key = it.next().toString();
System.out.print(key + "=>");
System.out.println(jsonObj.get(key));
}
} catch(JSONException ex) {
ex.printStackTrace();
}
}
}
jsonObj.get(key);return an Object, you need to cast it to a String if you want to get the value in a String variable. There is a getString method in the JSONObject class:And you don’t get any error in your test class as you’re only outputting the value that is calling the toString() method.