从JSON文件中获取值和名称

时间:2016-01-05 11:35:08

标签: android json android-json

我的json回复:

    {
    "Countries": [

        {

                "Country": "China",
                "Alpha2": "CN",
                "Alpha3": "CHN",

                "numbers": {
                    "Jon": "100",
                    "Mat": "200",
                    "SAM": "300"


                }
        },
         {

                "Country": "Italy",
                "Alpha2": "IT",
                "Alpha3": "ITA",

                "numbers": {
                    "Benny": "400",
                    "Jack": "500"


                }
         }

    ]
}

我的代码:

for (int i = 0; i < m_jArry.length(); i++) {
            JSONObject jo_inside = m_jArry.getJSONObject(i);

            if (jo_inside.getString("Country").equals("Italy"))
            {
                Log.d("DTAG",jo_inside.getString("Country"));
                Log.d("DTAG",jo_inside.getString("Alpha2"));
                Log.d("DTAG", jo_inside.getString("Alpha3"));

                JSONObject jo_inside2 = jo_inside.getJSONObject("numbers");
                Log.d("DTAG", "Size: "+jo_inside2.length());

                for (int j=0;j<jo_inside2.length();j++)
                {
                    //???
                }
            }

我如何获得价值名称及其价值? 对于这个例子,我需要得到Benny 400,Jack 500

4 个答案:

答案 0 :(得分:2)

您可以使用json.keys获取所有密钥,在您的情况下,请尝试使用以下代码。

  Iterator<String> iter = jo_inside2.keys();
  while (iter.hasNext()) {
    String key = iter.next();
    try {
        Object value = jo_inside2.get(key);
    } catch (JSONException e) {
        //exception
    }
  }

答案 1 :(得分:2)

 if (jo_inside.getString("Country").equals("Italy"))
            {
                Log.d("DTAG",jo_inside.getString("Country"));
                Log.d("DTAG",jo_inside.getString("Alpha2"));
                Log.d("DTAG", jo_inside.getString("Alpha3"));

                JSONObject jo_inside2 = jo_inside.getJSONObject("numbers");
                Log.d("DTAG", "Size: "+jo_inside2.length());

                for (int j=0;j<jo_inside2.length();j++)
                {
                    Iterator<?> keys = jo_inside2.keys();

                while( keys.hasNext() ) 
                  {
                   String key = (String)keys.next();
                    if ( jo_inside2.get(key) instanceof JSONObject ) 
                     {
                           Object value = jo_inside2.get(key);
                     }
                   }
                  }
            }

答案 2 :(得分:1)

//从JSONObj获取所有密钥

    Iterator<String> iterator = jo_inside2.keys();
      while (iterator.hasNext()) {
        String key = iterator.next();
        Log.i("TAG","key:"+key +"--Value::"+categoryJSONObj.optString(key);

  }

答案 3 :(得分:0)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
  <div class="box"></div>
  <div class="box-2"></div>
</div>

<div class="box"></div>