fastjson提取json返回值(java)

返回json数据:

{
    "data": {
        "offset": 2,
        "total": 2952,
        "restTotal": 2950,
        "dataList": [{
            "ISBN": "9787539197456",
            "bookStar": "93.6",
            "tag": "",
            "commentTimes": "1487",
            "price": "58.00",
            "star50Percent": "",
            "star40Percent": "",
            "star30Percent": "",
            "star20Percent": "",
            "star10Percent": ""
        }, {
            "ISBN": "9787539197449",
            "bookStar": "95.8",
            "tag": "",
            "commentTimes": "15711",
            "price": "25.00",
            "star50Percent": "",
            "star40Percent": "",
            "star30Percent": "",
            "star20Percent": "",
            "star10Percent": ""
        }]
    },
    "error": "success",
    "error_Description": "操作成功"
}

使用fastjson取值:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;



{
        JSONObject json_o = GetJson(调用接口的方法,得到返回值);//方法就是一个Httpclient的get

        //得到data的json对象
        JSONObject jsondata = JSON.parseObject(json_o.getString("data"));
        //得到data中的dataList对象,并用jsonarray保存
        JSONArray jsonarr = jsondata.getJSONArray("dataList");
        //使用for循环遍历datalist里的json值,如:price,ISBN
        for(int i = 0;i<jsonarr.size();i++){
            JSONObject jsonb = jsonarr.getJSONObject(i);
            String price = jsonb.getString("price");
            String ISBN = jsonb.getString("ISBN");
            //其他值的获取相同.取到值后再入库
        }
        //获取total值
        String total = jsondata.getString("total");
        //获取error值
        String error = json_o.getString("error"));

}

fastjson文档参考:https://www.w3cschool.cn/fastjson/fastjson-api.html

posted @ 2022-12-26 17:50  进击的bug~  阅读(713)  评论(0编辑  收藏  举报