-1

私はこの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を解析する必要があります。私を助けてください

4

3 に答える 3

2

これはJSONArrayによって解析されることを意図しており、各「レコード」はJSONObjectです。

配列をループしてから、 getString(int)メソッドを使用して各レコードのJSON文字列を取得できます。次に、この文字列を使用してJSONObjectを作成し、今と同じように値を抽出します。

于 2013-01-27T20:57:31.670 に答える
2

次のようになります。

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;
}

もちろん、名前の配列など、必要なものは何でも返す必要があります。

于 2013-01-27T20:58:21.977 に答える
1

次のコードを使用できます。

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();
    }
}

データを保存または使用するには、ループを変更する必要があります。

それが役に立てば幸い。

于 2013-01-27T21:03:49.487 に答える