How to fetch Data From JSON

2020-05-06 00:55发布

问题:

I have following data from JSON

{
        "MenuName": "starter dish",
        "SubMenu": [
            "pizza dish1",
            "pizza dish2"
        ],
        "Price": [
            "100",
            "110"
        ]
    },

From here i can easily fetch data from "Menuname" key as starter dish but when I fetch data from "Submenu" I get whole string as ["pizza dish1", "pizza dish2"].

Please suggest me way to differentiate both pizza dish1 and pizza dish2

回答1:

Submenu and Price is not String it is JSONArray so you will need to use for-loop to get all values from Submenu JSONArray as:

JSONArray jsonsubmenu=yourjsonobject.getJSONArray("Submenu");

  for(int i=0;i < jsonsubmenu.length();i++){     
     // get all values from jsonsubmenu JSONArray..
      String str_value=jsonsubmenu.optString(i);
      ....
   }


回答2:

try this

          for (int i = 0; i < jsonArray.length(); i++) {
             jsonArray.getJSONObject(i).getInt("SubMenu");
             }


回答3:

you can use this link for creating POGO class for your response. It will automatically generate class for your response.

Use google GSON library to parse your response.

or you can simply create a JSON Array or Objects to parse it. in your case it is JSON Object or JSON arrays.



回答4:

Hi There in that senarerio you have to use

    JSONArray _submenu = object.getJSONArray("SubMenu");
        for (int i = 0; i < _submenu.length(); i++) {
            String text = _submenu.getString(i);
        }
        JSONArray _price = object.getJSONArray("Price");
        for (int i = 0; i < _price.length(); i++) {
            String text = _price.getString(i);
        }


回答5:

You can retrieve array values and store it in string[] and use them as per your need. i.e., as follows..

try {
            JSONObject jObject = new JSONObject(jsonString);
            JSONArray jSubmenu = jObject.getJSONArray("SubMenu");
            subMenu = new String[jSubmenu.length()];
            for (int i = 0; i < subMenu.length; i++) {
                subMenu[i] = jSubmenu.getString(i);
            }
            JSONArray jPrice = jObject.getJSONArray("Price");
            price = new String[jPrice.length()];
            for (int i = 0; i < price.length; i++) {
                price[i] = jPrice.getString(i);
            }

        } catch (Exception e) {
            // TODO: handle exception
        }


回答6:

Just to throw in a quickie - read up on, and use GSON.

For simple small jobs I find it is the best. Not the fastest running for complex, or long structures, but really quick on the dev side.

Here's the link: google-gson