[英]How to Parse this JSON Response in JAVA
I want to parse these kind of Json responses : 我想解析这些Json响应:
{
"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"
}]
}
}
I tried using SIMPLE JSON parser but this is not working for me: 我尝试使用SIMPLE JSON解析器,但这对我不起作用:
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);
}
}
Output: 输出:
[vignesh1, vignesh2, vignesh3]
Comment: I didn't add validation 评论:我没有添加验证
[EDIT] [编辑]
other way to load json String 加载json String的其他方法
JSONObject obj= new JSONObject();
JSONObject jsonObject = obj.fromObject(jsonString);
....
You can do simply: 你可以做到:
JSONObject response = new JSONObject(resp);
Then you can use depending on the type of the variable something like: 然后你可以根据变量的类型使用:
int count = response.getint("count");
or 要么
JSONArray tsm = response.getJSONArray(listTsm)
Then if you want to iterate through the objects inside you use just a for for it. 然后,如果你想遍历内部的对象,你只需要使用for。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.