Gson是更流行的解析json的库里,我自己一把很喜欢用Gson来解析,因为直接可以写对象和json文件相对应
对于一个标准的后台返回:
{ "data": { "product_info": { "name": "澳斯贝贝 婴儿长袖水晶绒睡袋 100cm 4", "image": "http://img01.meituncdn.com/group2/M00/00/78/rBABnFVMXPqAKlu5AAD9lKlBSzE063.jpg", "stock": 0 }, "task_list": [ { "task_id": 4, "status": "进行中" } ] }, "status": "success", "message": null }
我们可以这样来构造解析对象:
public class HistoryResponse { public HistoryData data; public String status; public String message; }
public class ProductInfo { public String name; public String image; public int stock; }
public class HistoryData { public ProductInfo product_info; public ArrayList<Tasks> task_list; }
public class Tasks { public int id; public String status; }
解析代码很简洁:
public void parseAssertDataUseGson() { InputStream is = null; try { is = this.getAssets().open("json2.json", Context.MODE_PRIVATE); int length = is.available(); byte[] buffer = new byte[length]; is.read(buffer); Reader response = new StringReader(new String(buffer)); Gson gson = new Gson(); HistoryResponse mydata = gson.fromJson(response,HistoryResponse.class); Log.d("TAG","<<<<mydata="+mydata.data.task_list.get(0).status); } catch (IOException ex) { ex.printStackTrace(); } }
代码在https://github.com/nickgao1986/StepSport
有一点要注意,对于
[
{
"booid": 1,
"bookName": "aa",
"icon": "http://pij4ed5ao.bkt.clouddn.com/1.jpg",
"book_description": "aa1"
},
{
"booid": 2,
"bookName": "bb",
"icon": "http://pij4ed5ao.bkt.clouddn.com/22.jpg",
"book_description": "bb1"
},
{
"booid": 3,
"bookName": "cc",
"icon": "http://pij4ed5ao.bkt.clouddn.com/33.jpeg",
"book_description": "cc1"
}
]
这样的json,我们需要用以下来解析
private void parseResponse(String response) { try{ Gson gson = new Gson(); JSONArray jsonArray = new JSONArray(response); ArrayList<Book> books; mBookResponse = new Gson().fromJson(response, new TypeToken<List<Book>>(){}.getType()); }catch (Exception ex) { ex.printStackTrace(); } }
public class Book { public int booid; public String bookName; public String icon; public String book_description; }
才不会出错
如果json出现java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 81这个问题,就代表解析器expected是一个array不过
实际解析的是一个jsonObject的错误
共同学习,写下你的评论
评论加载中...
作者其他优质文章