如何阅读这种JSON格式

时间:2018-05-10 06:23:23

标签: android json retrofit2

我的JSON:

[
  {
    "productid": "3",
    "name": "Potato",
    "price": "15",
    "quantity": "",
    "stock": "0",
    "description": "Fresh and good",
    "image1": "upload/Potato1.jpg",
    "image2": "upload/Potato2.jpg",
    "image3": "upload/Potato3.jpg",
    "status": "Out of Stock",
    "type": "Vegetables"
  },
  {
    "productid": "5",
    "name": "Tomato",
    "price": "25",
    "quantity": "",
    "stock": "45",
    "description": "Fresh and good",
    "image1": "upload/Tomato1.jpg",
    "image2": "upload/Tomato2.jpg",
    "image3": "upload/Tomato3.jpg",
    "status": "Avaiable",
    "type": "Vegetables"
  },
  {
    "productid": "4",
    "name": "Onion",
    "price": "30",
    "quantity": "",
    "stock": "50",
    "description": "Fresh and good",
    "image1": "upload/Onion1.jpg",
    "image2": "upload/Onion2.jpg",
    "image3": "upload/Onion3.jpg",
    "status": "Avaiable",
    "type": "Vegetables",
    "wishlistid": "43",
    "userid": "10",
    "flag": "1"
  },
  {
    "productid": "6",
    "name": "Carrot",
    "price": "20",
    "quantity": "",
    "stock": "50",
    "description": "Fresh and good",
    "image1": "upload/Carrot1.jpg",
    "image2": "upload/Carrot2.jpg",
    "image3": "upload/Carrot3.jpg",
    "status": "Avaiable",
    "type": "Vegetables",
    "wishlistid": "47",
    "userid": "10",
    "flag": "1"
  }
]

在前2个json对象中,有少量列丢失,如userid和wishlistid以及flag,其余的都有useridwishlistidflag

如何通过改装库来阅读本文...因为它没有给我任何信息,因为在前2个对象中找不到userid列。

1 个答案:

答案 0 :(得分:0)

你可以使用像Gson这样的解析器来解析json牵引方式,也可以使用其他解析器,也可以更好地为你创建帮助你的pojo类。

String yourJsonString=jsondata;
        JSONArray  jsonArray= null;
        try {
            jsonArray = new JSONArray(yourJsonString);
            if(jsonArray!=null && jsonArray.length()>0){

                //Here you can parse tow way one is manual or other one using gson

                //1.Manual one
                for(int pos=0;pos<jsonArray.length();pos++){
                    JSONObject jsonObject=jsonArray.getJSONObject(pos)
                    //Here you can parse your object tow one is pass all value by manual
                    //like YourModelObject.setMethod(jsonObject.getString("keyName");

                    //Or other one is create model class and parse data using gson like following
                    /*CustomModel modelObj= new Gson().fromJson(jsonObject, new TypeToken<LocationHoModel>() {
                    }.getType());*/


                }

                //2.Using Gson
                /*ArrayList<CustomModel> customModelArrayList = new Gson().fromJson(jsonArray, new TypeToken<ArrayList<CustomModel>>() {
                }.getType());*/

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