如何在JAVA中解析此JSON响应 [英] How to Parse this JSON Response in JAVA
本文介绍了如何在JAVA中解析此JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想解析这些Json回复:
I want to parse these kind of Json responses :
{
"MyResponse": {
"count": 3,
"listTsm": [{
"id": "b90c6218-73c8-30bd-b532-5ccf435da766",
"simpleid": 1,
"name": "vignesh1"
},
{
"id": "b90c6218-73c8-30bd-b532-5ccf435da766",
"simpleid": 2,
"name": "vignesh2"
},
{
"id": "b90c6218-73c8-30bd-b532-5ccf435da766",
"simpleid": 3,
"name": "vignesh3"
}]
}
}
我尝试使用SIMPLE JSON解析器,但这对我不起作用:
I tried using SIMPLE JSON parser but this is not working for me:
Object obj = parser.parse(resp);
JSONObject jsonObject = (JSONObject) obj;
JSONArray response = (JSONArray) jsonObject.get("MyResponse");
//JSONArray arr=new JSONArray(yourJSONresponse);
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<response.size(); i++){
list.add(response.get(i)("name"));
}
推荐答案
public static void main(String[] args) throws JSONException {
String jsonString = "{" +
" \"MyResponse\": {" +
" \"count\": 3," +
" \"listTsm\": [{" +
" \"id\": \"b90c6218-73c8-30bd-b532-5ccf435da766\"," +
" \"simpleid\": 1," +
" \"name\": \"vignesh1\"" +
" }," +
" {" +
" \"id\": \"b90c6218-73c8-30bd-b532-5ccf435da766\"," +
" \"simpleid\": 2," +
" \"name\": \"vignesh2\"" +
" }," +
" {" +
" \"id\": \"b90c6218-73c8-30bd-b532-5ccf435da766\"," +
" \"simpleid\": 3," +
" \"name\": \"vignesh3\"" +
" }]" +
" }" +
"}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject myResponse = jsonObject.getJSONObject("MyResponse");
JSONArray tsmresponse = (JSONArray) myResponse.get("listTsm");
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<tsmresponse.length(); i++){
list.add(tsmresponse.getJSONObject(i).getString("name"));
}
System.out.println(list);
}
}
输出:
[vignesh1, vignesh2, vignesh3]
评论:我没有添加验证
加载json的其他方式String
other way to load json String
JSONObject obj= new JSONObject();
JSONObject jsonObject = obj.fromObject(jsonString);
....
这篇关于如何在JAVA中解析此JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文