how to deserialize json to a dictionary or keyvaluepair?
I have to deserialize a JSON object like this
[{"Key":{"id":0, "Name":"an Object"}, "Value":true},
{"Key":{开发者_如何学C"id":0, "Name":"an Object"}, "Value":true}]
I know how to deserialize arrays and singleobjects or variables. but I'm in the blue about dictionaries.
I'm using the following to read an array
NetworkEvent n = (NetworkEvent) evt;
byte[] data = (byte[]) n.getMetaData();
AnObject[] anObject= null;
try {
JSONArray json = new JSONArray(new String(data, "UTF-8"));
anObject= AnObject.getAnObjects(json);
} catch (Exception ex) {
ex.printStackTrace();
}
The final code solution:
Object[] objects= new Object[json.length()];
for (int i = 0; i < json.length(); ++i) {
Key key= null;
Value value = null;
try {
JSONObject keyValuePair = json.getJSONObject(i);
key= Key.getKey(keyValuePair.getJSONObject("Key"));
value= keyValuePair.getBoolean("Value");
} catch (JSONException ex) {
ex.printStackTrace();
}
Object object= new object();
object.setKey(key);
object.setValue(value);
Objects[i] = object;
}
return objects;
What you have there is not a JSON object. It is an array of JSON objects, and therefore your current code should work.
I think that your "problem" is that you are using the wrong terminology.
This is an attribute or name/value pair:
"id":0
This is an object:
{"id":0, "Name":"an Object"}
This is also an object:
{"Key":{"id":0, "Name":"an Object"}, "Value":true}
This is an array (of objects)
[{"Key":{"id":0, "Name":"an Object"}, "Value":true},
{"Key":{"id":0, "Name":"an Object"}, "Value":true}]
For more details, refer to the json.org site.
Try the Jackson library.
精彩评论