【发布时间】:2010-12-27 14:07:22
【问题描述】:
我必须像这样反序列化一个 JSON 对象
[{"Key":{"id":0, "Name":"an Object"}, "Value":true},
{"Key":{"id":0, "Name":"an Object"}, "Value":true}]
我知道如何反序列化数组和单个对象或变量。但我对字典一无所知。
我正在使用以下内容来读取数组
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();
}
最终代码解决方案:
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;
【问题讨论】:
标签: java json network-programming