【问题标题】:How to parse this kind of json? [duplicate]如何解析这种json? [复制]
【发布时间】:2023-03-03 08:53:22
【问题描述】:
[
  {

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

  {

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

  {

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

我有这种来自 api 的 json

【问题讨论】:

标签: android json android-studio android-fragments


【解决方案1】:

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

 [
 {

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

【讨论】:

  • 如何在 textview 上设置。实际上点设置在 3 个不同的 Textview 上
  • 尝试更新答案...对于三个 TextView... 设置
  • 你解决了这个问题吗?还是有问题
【解决方案2】:

[] 内的任何东西都被认为是 JSONArray 元素---> 在这种情况下,它是一个包含 JSONObject 的 JSONArray

假设 JSON 类似于:

{ 

  abc: [
     {"name":"kushan"}

  ]

}

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

有一个来自 google 的 GSON,有简单的 JSON、org.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
}

【讨论】:

    猜你喜欢
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2013-06-27
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2012-05-24
    相关资源
    最近更新 更多