欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

fastjson包将json字符串转为map及转为List(Map)

程序员文章站 2022-07-15 13:25:41
...

https://www.cnblogs.com/libin6505/p/12091705.html

假设返回报文为:

fastjson包将json字符串转为map及转为List(Map)
对应字符串:
{“customer”: [{“controlLevel”: “13013001”,“commonRegionName”: “集团”,“createDate”: “”,“custId”: “4164275”,“partyNumber”: “LN2018122110041351”,“extCustId”: “”,“statusCd”: “”,“controlType”: “13013001”,“ChannelMemberId”: “”,“commonRegionId”: “100000”,“custNumber”: “1000001994420000”,“custName”: “华夏银行股份有限公司鞍山分行”,“industryCd”: “DD0302”}]}

下面代码对其进行解析,其中包括转为Map、转为List
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public static void main(String[] args) {
    String s = "{\"customer\": [{\"controlLevel\": \"13013001\",\"commonRegionName\": \"集团\",\"createDate\": \"\",\"custId\": \"4164275\",\"partyNumber\": \"LN2018122110041351\",\"extCustId\": \"\",\"statusCd\": \"\",\"controlType\": \"13013001\",\"ChannelMemberId\": \"\",\"commonRegionId\": \"100000\",\"custNumber\": \"1000001994420000\",\"custName\": \"华夏银行股份有限公司鞍山分行\",\"industryCd\": \"DD0302\"}]}";
    //将json字符串转为map对象
    JSONObject jsonObject = JSONObject.parseObject(s);
    Map<String,Object> map = (Map<String,Object>)jsonObject;
    //将Map中符合数组结构的字符串转为list对象,list对象中是Map
    String s2 = map.get("customer")+"";
    System.out.println(s2);
    List<Map> list = JSONObject.parseArray(s2, Map.class);//这里的第二个参数也可以用对应的自定义javaBean.class
    //遍历其中的map,取出每个属性值
    for (Map item : list) {
        System.out.println(item.get("custId"));
    }
}

控制台输出:

[{"custId":"4164275","partyNumber":"LN2018122110041351","ChannelMemberId":"","controlType":"13013001","commonRegionName":"集团","industryCd":"DD0302","commonRegionId":"100000","extCustId":"","statusCd":"","custNumber":"1000001994420000","custName":"华夏银行股份有限公司鞍山分行","createDate":"","controlLevel":"13013001"}]
4164275