java解析复杂json:JSONObject 和 JSONArray的使用
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json

·
在正式解析之前,我们需要下载解析Json所需要的jar包,一共有7个。
下载地址如下:https://download.csdn.net/download/zai_xia/10374080
大家也可以自行找资源下载。
然后将这些Jar包 Build Path 进项目就好了。
特别注意:commons-collections这个jar包要用3.x版本的,不能用4.x版本;commons-lang这个jar包要用2.x版本的,不能用3.x版本的。
我们的目的是解析下面这样的json内容:
{
"data":{
"items":[
{
"itemstring":"手机",
"itemcoord":{"x":0,"y":100,"width":40,"height":20},
}
],
"session_id":"",
},
"code":0,
"message":"OK"
}
代码如下:
package format;
import net.sf.json.*;
public class ResolveJson {
public static void main(String[] args) {
String json = "{\"data\":{\"items\":[{\"itemstring\":\"手机\",\"itemcoord\":{\"x\":0,\"y\":100,\"width\":40,\"height\":20},}],\"session_id\":\"\",},\"code\":0,\"message\":\"OK\"}";
JSONObject jsonObject = JSONObject.fromObject(json);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray items = jsonObject.getJSONObject("data").getJSONArray("items");
JSONObject row = null;
for(int i=0; i<items.size(); i++){
row = items.getJSONObject(i);
System.out.println("itemstring :" + row.get("itemstring"));
JSONObject itemcoord = row.getJSONObject("itemcoord");
System.out.println("x:" + itemcoord.get("x"));
System.out.println("y:" + itemcoord.get("y"));
System.out.println("width:" + itemcoord.get("width"));
System.out.println("height:" + itemcoord.get("height"));
}
System.out.println("session_id:" + data.get("session_id"));
System.out.println("code:" + jsonObject.get("code"));
System.out.println("code:" + jsonObject.get("message"));
}
}
运行结果:
其实解析过程就是将json看情况转换成JSONObject对象或JSONArray数组,再进行下一步处理,最终得到目的值。




适用于现代 C++ 的 JSON。
最近提交(Master分支:5 个月前 )
34665ae6
binary -> binary_t
Signed-off-by: Robert Chisholm <robert.chisholm@sheffield.ac.uk> 21 天前
f3dc4684
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.9 to 3.28.10.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0...b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d)
---
updated-dependencies:
- dependency-name: github/codeql-action
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 28 天前
更多推荐
所有评论(0)