Dem*_*ier 2 java json network-programming
我必须像这样反序列化一个JSON对象
[{"Key":{"id":0, "Name":"an Object"}, "Value":true},
{"Key":{"id":0, "Name":"an Object"}, "Value":true}]
Run Code Online (Sandbox Code Playgroud)
我知道如何反序列化数组和单个对象或变量.但我对词典却很沮丧.
我正在使用以下内容来读取数组
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();
}
Run Code Online (Sandbox Code Playgroud)
最终的代码解决方案:
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;
Run Code Online (Sandbox Code Playgroud)
你所拥有的不是JSON对象.它是一个JSON对象数组,因此您当前的代码应该可以工作.
我认为你的"问题"是你使用了错误的术语.
这是属性或名称/值对:
"id":0
Run Code Online (Sandbox Code Playgroud)
这是一个对象:
{"id":0, "Name":"an Object"}
Run Code Online (Sandbox Code Playgroud)
这也是一个对象:
{"Key":{"id":0, "Name":"an Object"}, "Value":true}
Run Code Online (Sandbox Code Playgroud)
这是一个数组(对象)
[{"Key":{"id":0, "Name":"an Object"}, "Value":true},
{"Key":{"id":0, "Name":"an Object"}, "Value":true}]
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅json.org站点.