如何在 JAVA 中解析这个 JSON 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18899232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Parse this JSON Response in JAVA
提问by user2463283
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"));
}
采纳答案by Maxim Shoustin
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字符串的其他方式
JSONObject obj= new JSONObject();
JSONObject jsonObject = obj.fromObject(jsonString);
....
回答by Nino Matos
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 即可。