【问题标题】:Android JSON Object ParsingAndroid JSON 对象解析
【发布时间】:2023-03-05 14:08:01
【问题描述】:

我有一些仅包含对象的示例 json 数据。

{
  "0": {
    "image": null,
    "title": "Government to issue new ₹500 and ₹2,000 notes from Nov 10 ",
    "time": "10:46 pm ",
    "date": "08 Nov ",
    "content": "The government will start issuing the new ₹500 and ₹2,000 currency notes from November 10, said ...",
    "link": "https://full-story.newsinshorts.com/v1/article/f0619b6a-738e-4470-897f-4e5cdad3ea52-1 "
  },
  "1": {
    "image": null,
    "title": "₹1,000, ₹5,000 and ₹10,000 notes were demonetised in 1978 ",
    "time": "10:20 pm ",
    "date": "08 Nov ",
    "content": "The Indian government had demonetised the ₹1,000, ₹5,000 and ₹10,000 currency notes in 1978 ...",
    "link": null
  },
  ...

}

它的对象比可见的要多。如何继续解析这些数据?

【问题讨论】:

  • 你可以试试this sample,我看到它几乎和你的json一样。
  • 你为什么尝试使用 GSON 将其解析为模型类并使用该模型
  • @Saveen - 你如何创建一个名为 0 的对象?
  • @Cricket_007 先生,这个 json 不正确,需要 json 数组

标签: android json


【解决方案1】:

我假设上面的 JSON 是从给定的来源获得的,比如 web 服务器。我就是这样处理的

   String yourJSON = {
          "0": {
            "image": null,
            "title": "Government to issue new ₹500 and ₹2,000 notes from Nov 10 ",
            "time": "10:46 pm ",
            "date": "08 Nov ",
            "content": "The government will start issuing the new ₹500 and ₹2,000 currency notes from November 10, said ...",
            "link": "https://full-story.newsinshorts.com/v1/article/f0619b6a-738e-4470-897f-4e5cdad3ea52-1 "
          },
          "1": {
            "image": null,
            "title": "₹1,000, ₹5,000 and ₹10,000 notes were demonetised in 1978 ",
            "time": "10:20 pm ",
            "date": "08 Nov ",
            "content": "The Indian government had demonetised the ₹1,000, ₹5,000 and ₹10,000 currency notes in 1978 ...",
            "link": null
          },
          ...

        };

        // create a JSON object to handle the response JSON
        JSONObject yourJSONObject = new JSONObject(yourJSON);

        /*
        *this converts entire JSON object to JSON array since there is no further nesting
        *this can be placed in a loop and the 0 replaced by an incremental variable say "int i"
        */
        JSONArray data = yourJSONObject.getJSONArray(String.valueOf(0));

        // loop through the items in the first JSON array which in this case is only one therefore at index 0
        for (int i = 0; i < data.length(); i++) {
            // create JSON object to hold each item in array
            JSONObject json = null;

            try {
                //Getting json
                json = data.getJSONObject(i);

                String image = json.getString("image");
                String title = json.getString("title");
                String time = json.getString("time");
                String date = json.getString("date");
                String content = json.getString("content");
                String link = json.getString("link");

                // perform action on this specific item


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

【讨论】:

  • getJSONArray(0) 编译吗?
  • 根据文档,该方法不存在。无论如何,该 JSON 中没有数组
  • 它确实可以编译,因为这是我的一个 Android 项目中的代码摘录
  • 虽然方法签名是getJSONArray(String name),但不是整数...正如我所说,JSON 中没有任何数组
  • 确保它是字符串。对不起误导。将其设为 "0" 或者如果您使用的是增量变量,请说 int i 然后执行 0+""+i
【解决方案2】:

好的……

尝试这样的事情......只是给你一个想法......

MyObject myObject = null;
JSONObject object = new JSONObject(response);
try{
    myObject = new MyObject();
    int position = 0;
    while(position < 100){
        JSONObject jsonObject = object.getJSONObject(String.valueOf(position));
        String title = jsonObject.getString("title");
        myObject.setTitle(title);

        ...


        position++;
    }
}catch (JSONException e){
    return e.getMessage();
}finally{
    return myObject;
}

【讨论】:

    【解决方案3】:

    尝试这种方式,我有相同的 json 响应,它对我有用

    class LoadAllStates extends AsyncTask<String, String, ArrayList<String>> {
        private ProgressDialog pDialog;
        private String test;
        private ArrayList<String> statedata;
        private ArrayList<String> idadddata;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ShippingAddress.this.getActivity());
            pDialog.setMessage("Please wait..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(true);
            pDialog.show();
        }
    
        protected ArrayList<String> doInBackground(String... args) {
            ServiceHandler sh = new ServiceHandler();
            // Making a request to url and getting response
            statedata = new ArrayList<String>();
    
            idadddata = new ArrayList<String>();
    
    
            String jsonStr = sh.makeServiceCall(GET_ADDRESS_DETAIL, ServiceHandler.GET);
            Log.d("Response: ", "> " + jsonStr);
            if (jsonStr != null) {
                try {
    
                    jsonObj = new JSONObject(jsonStr);
                    for (int i = 1; i <= jsonObj.length(); i++) {
    
                        JSONObject user = jsonObj.getJSONObject(""+i);
    
    
                        idaddress=String.valueOf(i);
                        System.out.println("userr"+i);
    
                        username= (user.has("name")) ? user.getString("name") : null;
                        usermobile= (user.has("mobile_number")) ? user.getString("mobile_number") : null;
                        useraddress= (user.has("address")) ? user.getString("address") : null;
                        userlandmark= (user.has("landmark")) ? user.getString("landmark") : null;
                        usercity= (user.has("city")) ? user.getString("city") : null;
                        userstate= (user.has("state")) ? user.getString("state") : null;
                        userpincode= (user.has("pin_code")) ? user.getString("pin_code") : null;
                        useremail= (user.has("email")) ? user.getString("email") : null;
                        if(username!=null)
                            statedata.add(username+","+usermobile+","+useraddress+","+userlandmark+","+usercity+","+userstate+","+userpincode+","+useremail);
    
                        idadddata.add(idaddress);
                        Log.i("inner",user.toString());
                    }
                    System.out.println("WifeBday"+statedata.size());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }
            return statedata;
        }
    
        protected void onPostExecute(ArrayList<String> result) {
            super.onPostExecute(result);
            pDialog.dismiss();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 2016-11-20
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多