android - 如何阅读这种 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
,wishlistid
和flag
.
userid
我怎么能用改造库来阅读这个.. 因为它没有给我任何东西,因为在前 2 个对象中没有找到列。
解决方案
您可以使用 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();
}
推荐阅读
- python - AttributeError:“NumpyArrayIterator”对象没有属性“ndim”
- java - 表 JAVA GUI 没有输出
- module - 如何找出 Prolog 运算符来自哪个模块?
- java - 如何将 JComboBox 作为 JList 中的元素?
- python - 将视图添加到 jupyter notebook 中的交互式 matplotlib 图
- javascript - 下载内容前刷新页面?
- asp.net-core - IIS 永久重定向到旧 URL 的一部分
- sql - ID 在 table1 中可用但在 table2 中不可用,请按日期检查
- mapbox - MapTiler 用透明海洋设置土地多边形填充
- node.js - **node-sass:当 rails new APP_PATH 命令失败**