在android中解析复杂的json

在android中解析复杂的json,android,json,parsing,Android,Json,Parsing,我有一个json: [{"id":"1","name":"john"},{"id":"2","name":"jack"},{"id":"3","name":"terry"}] 我如何解析这个?我必须使用循环来提取每个组?对于简单的JSON,我使用以下代码: public static String parseJSONResponse(String jsonResponse) { try { JSONObject json = new JSONObject

我有一个json:

[{"id":"1","name":"john"},{"id":"2","name":"jack"},{"id":"3","name":"terry"}]
我如何解析这个?我必须使用循环来提取每个组?对于简单的JSON,我使用以下代码:

    public static String parseJSONResponse(String jsonResponse) {

    try {

         JSONObject  json = new JSONObject(jsonResponse);

           // get name & id here
         String  name = json.getString("name");
         String  id =  json.getString("id");

    } catch (JSONException e) {

        e.printStackTrace();
    }

    return name;
}

但现在我必须解析我的新json。请帮助我

这意味着要由一个JSONArray解析,然后每个“记录”都是一个JSONObject


您可以在数组上循环,然后使用该方法检索每个记录的JSON字符串。然后使用此字符串构建一个JSONObject,然后像现在一样提取值。

应该是这样的:

public static String parseJSONResponse(String jsonResponse) {

try {

    JSONArray jsonArray = new JSONArray(jsonResponse);

    for (int index = 0; index < jsonArray.length(); index++) {
        JSONObject  json = jsonArray.getJSONObject(index);

        // get name & id here
        String  name = json.getString("name");
        String  id =  json.getString("id");
    } 



} catch (JSONException e) {

    e.printStackTrace();
}

return name;
}
publicstaticstringparsejsonresponse(stringjsonresponse){
试一试{
JSONArray JSONArray=新的JSONArray(jsonResponse);
for(int index=0;index

当然,您应该返回名称数组或您想要的任何内容。

您可以使用以下代码:

public static void parseJSONResponse(String jsonResponse) {

    try {

        JSONArray jsonArray = new JSONArray(jsonResponse);     
        if(jsonArray != null){
            for(int i=0; i<jsonArray.length(); i++){
                JSONObject json = jsonArray.getJSONObject(i);
                String  name = json.getString("name");
                String  id =  json.getString("id"); 
                //Store strings data or use it
            }
        }
    }catch (JSONException e) {
        e.printStackTrace();
    }
}
publicstaticvoidparsejsonresponse(字符串jsonResponse){
试一试{
JSONArray JSONArray=新的JSONArray(jsonResponse);
if(jsonArray!=null){
对于(int i=0;i