如何解析这种json?

时间:2016-08-10 06:43:56

标签: android json android-studio android-fragments

[
  {

    "points": 411,
    "type": "C"
  },

  {

    "points": 1600,
    "type": "G"
  },

  {

    "points": 13540,
    "type": "I"
  }
]

我有这种来自api的json

2 个答案:

答案 0 :(得分:0)

  

注意:**第二个阵列数据中缺少{ .....

 [
 {

"points": 411,
"type": "C"
},

{
"points": 1600,
"type": "G"
},

{

 "points": 13540,
"type": "I"
} 
 ]
  

<强>代码

 try {
        JSONArray jsonArray=new JSONArray(Response);
        for(int i=0;i<jsonArray.length();i++)
        {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            int points=jsonObject.getInt("points");
            String type=jsonObject.getString("type");

    // if you have only three textview. and three array data than set as like that... 

       if(i=0)
    {
        textview1.setText(String.valueOf(points));

    }
    else if(i==1)
    {
        textview2.setText(String.valueOf(points));
    }
    else
    { 
        textview3.setText(String.valueOf(points));

    }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

答案 1 :(得分:0)

[]内的任何内容都被视为JSONArray Elements ---&gt;在这种情况下,它是一个包含JSONObject

的JSONArray

所以让我们说JSON就像:

try{
   JSONObject obj= new JSONObject("StringcontainingJSON");
   JSONArray jsarr= obj.getJSONArray("abc");
   JSONObject innerObj= jsarr.getJSONObject(0); //0th position is the only element of the array
   String nameValue=innerObj.getString("name");

}catch(JSONException e){

   //any key value duplicate or invalid key or missing etc.. will throw the exception
}

你可以根据用来解析它的库来解析它....

来自谷歌的GSON,有简单的JSON,org.json等...

基本情景是:

function test(element_name){
  $("#"+element_name).show();
}