如何将 json 反序列化为字典或键值对?
我必须像这样反序列化 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;
I have to deserialize a JSON object like this
[{"Key":{"id":0, "Name":"an Object"}, "Value":true},
{"Key":{"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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你所拥有的不是 JSON 对象。它是一个 JSON 对象数组,因此您当前的代码应该可以工作。
我认为你的“问题”是你使用了错误的术语。
这是一个属性或名称/值对:
这是一个对象:
这也是一个对象:
这是一个(对象的)数组
有关更多详细信息,请参阅 json.org 网站。
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:
This is an object:
This is also an object:
This is an array (of objects)
For more details, refer to the json.org site.
尝试 Jackson 库。
Try the Jackson library.