从JSONArray获取特定值

时间:2015-04-10 18:43:33

标签: android json

我有一个jsonarray:

  [
    {
        "ean": "8020079127",
        "nr": "100",
        "name": "Name1"
    },
    {
        "ean": "8026180222",
        "nr": "4",
        "name": "Name2"
    },
    {
        "ean": "6577426092",
        "nr": "1",
        "name": "Name3"
    }
]

我需要来自" nr"的值取决于" ean"手段: 我得到了ean 8026180222(作为字符串)并且需要来自" nr"的值。 (这里" 4")。我怎么能得到它? 它可能没有迭代整个数组?

谢谢

2 个答案:

答案 0 :(得分:0)

List<NameValuePair> params = new ArrayList<NameValuePair>();

JsonObject json = jsonParser.makeHttpRequest(url, "GET", params);

                    Log.d("Tag", json.toString());

                    int success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        JSONArray jsnObj;
                        try {
                            jsnObj = json
                                .getJSONArray(TAG_ARRAY);
                            JSONObject obj = jsnObj
                                    .getJSONObject(1);
        String nr = obj.getString(TAG_NR);

                            }
                        Catch(Exception ex){}
                 }

          }

如果你想要数组你可以在json数组中使用循环.....................希望它会有所帮助

只需定义

   private static final String TAG_SUCCESS = "success";
   private static final String TAG_NR = "nr";
   private static final String TAG_ARRAY = "array_name";

答案 1 :(得分:0)

试试这个:

     // Use a map to store ean,nr (as key/value)
     HashMap<String, String> jsonMap = new HashMap<String, String>();

     // Load the data from json 
     JSONArray jsonArray= new JSONArray(yourJsonString);

     for (int i = 0; i < jsonArray.length(); i++) {

        JSONObject jsonObj = jsonArray.getJSONObject(i);

        String ean = jsonObj.getString("ean");
        String nr = jsonObj.getString("nr");
        String name = jsonObj.getString("name");
        jsonMap.put(ean, nr);  // here you put ean as key and nr as value
     }

要检索特定 ean nr 值,只需致电:jsonMap.get(yourEAN);

示例:String nr = jsonMap.get("8026180222");