java - JAVA中JsonObjects的JsonObject
问题描述
我有一个JSONObject
完整的JSONobject
s,我需要将它们中的每一个提取到一个新的中JSONObject
,以便我可以单独操作它们中的每一个,但我真的不知道该怎么做。我的代码是这样的:
public void loadBodies(InputStream in) {
JSONObject jsonInput= new JSONObject(new JSONTokener(in));
JSONObject jo2 = jsonInput.getJSONObject("bodies"); //probably incorrect
for(JSonObject j: jo2) b.create(j); //i need to apply the create method to all the JSONObjects
想象这样的 JSON
{'bodies': [
{
'total': 142250.0,
'_id': 'BC'
},
{
'total': 210.88999999999996,
'_id': 'USD'
},
{
'total': 1065600.0,
'_id': 'TK'
}
]
}
我需要将JSONObject
键下的所有 s提取bodies
到一个新的集合中JSONObjects
,以便我可以对它们进行操作。所以基本上,循环提取它们,但我不知道如何。
解决方案
根据您的示例,bodies
是一个 JSON 数组。所以使用JSONArray
库org.json:json
来迭代数组的内容:
String json = "{\"bodies\": [{\"total\": 142250.0, \"_id\": \"BC\"}]}";
JSONObject jsonInput = new JSONObject(new JSONTokener(new StringReader(json)));
JSONArray array = jsonInput.getJSONArray("bodies");
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
// implement here your logic on obj
}
推荐阅读
- php - 将json字符串转换为变量
- rx-java - 解耦服务调用和数据库存储
- postgresql - 使用表名限定时,Postgres 列引用不明确
- javascript - 获取你写的节点
- python - csv 文件显示 ... 而不是整个数据框
- java - 比较不同对象的列表并使用Stream在java8中构建新的对象列表
- java - Passing returned variables to other static methods for calculations
- javascript - 从firebase数据库表中检索列表中的数据
- html - getuikit 链接在下拉列表中不起作用
- bash - bash 脚本中的 $1 和 "$1" 有什么区别?