由于在实际工作中使用fastjson解析嵌套map的场景非常多,所以在此备忘一下:
引入阿里的fastjson的pom:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.15</version> </dependency>
一个比较复杂的json例子:
{ "actId": "1800025","originCode": 1,"role": "TEACHER","time": 1471077017804,"userId": "1111","userName": "测试教师","userIcon": "xyz","userIp": "1.1.1.1","countyId": "370105","countyName": "天桥区","schoolId": "1234","schoolName": "测试小学","data": { "subjectId": "020","subjectName": "数学","uploadFileList": [ { "teachFileType": "1","custom": "xtz" },{ "teachFileType": "1" } ] } }
使用fastjson的解析代码:
import com.alibaba.fastjson.JSON; import java.util.List; import java.util.Map; /** * Created by Administrator on 2016/8/12. */ public class ParserJson { /*** * * @param map 需要打印的Map结构 */ public static void showMap(Map<String,Object> map){ for(Map.Entry<String,Object> kv:map.entrySet()){ System.out.println(kv.getKey()+" "+kv.getValue()); } } public static void main(String[] args) throws Exception { String json="{\"actId\":\"2300003\",\"originCode\":1,\"role\":\"TEACHER\"" + ",\"time\":1470126407000,\"userId\":\"1111\",\"userName\":\"测试教师\",\"userIcon\":\"xyz\",\"userIp\":\"1.1.1.1\",\"countyId\":\"370105\",\"countyName\":\"天桥区\",\"schoolId\":\"1234\",\"schoolName\":\"测试小学\",\"data\":{\"subjectId\":\"020\",\"subjectName\":\"数学\"," + "\"uploadFileList\":[{\"teachFileType\":\"1\"},{\"teachFileType\":\"1\",\"custom\":\"xt\"},{\"teachFileType\":\"1\"}]}}"; Map<String,Object> map=(Map)JSON.parse(json); System.out.println("打印第一层map"); showMap(map); Map<String,Object> dataMap=(Map<String,Object>) map.get("data"); System.out.println("打印第二层map"); showMap(dataMap); System.out.println("打印第三层list+map"); List<Map<String,Object>> fileList= (List<Map<String,Object>>) dataMap.get("uploadFileList"); for(Map<String,Object> soj:fileList){ System.out.println(soj); Map<String,Object> detailData=soj; showMap(detailData); System.out.println("----------------------------------------"); } } }
解析结果:
ParserJson 打印第一层map role TEACHER data {"uploadFileList":[{"teachFileType":"1"},{"custom":"xt","teachFileType":"1"},{"teachFileType":"1"}],"subjectId":"020","subjectName":"数学"} actId 2300003 userName 测试教师 userId 1111 countyId 370105 schoolId 1234 userIp 1.1.1.1 originCode 1 time 1470126407000 userIcon xyz schoolName 测试小学 countyName 天桥区 打印第二层map uploadFileList [{"teachFileType":"1"},{"teachFileType":"1"}] subjectId 020 subjectName 数学 打印第三层list+map {"teachFileType":"1"} teachFileType 1 ---------------------------------------- {"custom":"xt","teachFileType":"1"} custom xt teachFileType 1 ---------------------------------------- {"teachFileType":"1"} teachFileType 1 ---------------------------------------- Process finished with exit code 0
有什么问题可以扫码关注微信公众号:我是攻城师(woshigcs),在后台留言咨询。
技术债不能欠,健康债更不能欠, 求道之路,与君同行。
原文链接:/json/289244.html