首页 > 解决方案 > 如何阅读这种 JSON 格式

问题描述

我的 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,其余的有userid,wishlistidflag.

userid我怎么能用改造库来阅读这个.. 因为它没有给我任何东西,因为在前 2 个对象中没有找到列。

标签: androidjsonretrofit2

解决方案


您可以使用 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();
        }

推荐阅读