大体上分为三步,1.准备json数据。2,导入fastjson包。3,编写代码测试。
一、准备要解析的json数据:(够复杂了吧)
{"code":200,"msg":"OK","data":{"result":1,"reportForms":[ {"id":1,"title":"testTitle","qNums":0,"brief":"This is test form","direction":"Parkinson","result":"0"},{"id":3,"title":"testTitle","qNums":0,"brief":"This is test form","direction":"Parkinson","result":"0"},{"id":4,"title":"testTitle","qNums":0,"brief":"This is test form","direction":"Parkinson","result":"0"},{"id":5,"title":"testTitle","qNums":0,"brief":"This is test form","direction":"Parkinson","result":"0"}]}}
二、导入fastjson依赖
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.73</version></dependency>
三、编写代码解析json
//fastjson解析复杂jsonpublic static void main(String[] args) {String url = "这里是你要访问的url地址";//1、获取复杂json数据,这个HttpRequestUtils.getRequest(url)方法是我自己封装的访问接口工具类(要看这个方法的话,文章末尾有链接)String request = HttpRequestUtils.getRequest(url);//2、先解析第一层json数据JSONObject data = JSON.parseObject(request);//3、再用解析到的data来解析第二层数据,同样得到jsonobjectJSONObject data1 = data.getJSONObject("data");//4、再套娃(同样是用data1来解析获得第三层json集合)JSONArray reportForms = data1.getJSONArray("reportForms");//5、如果这不是我们需要的那一层,则接下来可以继续按上面这种思路解析//5、如果是我们需要的那一层,则有好多种取值方法://第一种:直接用reportForms的get方法根据下标取出数据,取出的是什么数据类型就用什么接收reportForms.size();//获取长度Object reportForm = reportForms.get(0);System.out.println("第一种解析方式:"+reportForm);//第二种解析方式:将上面解析到的jsonArray数据直接用tojavalist方法转成list集合,然后遍历输出//注意:参数要带上想要转成的list集合类型ReportForm.class(这个类型是我自己定义的,只要和json数据中对照就可以了),然后遍历输出List<ReportForm> list = reportForms.toJavaList(ReportForm.class);System.out.println("=======第二种方式======");list.forEach(System.out::println);//第三种方式:直接将reportForms的迭代器获取到,通过迭代器遍历System.out.println("=====第三种方式========");Iterator<Object> iterator = reportForms.iterator();while (iterator.hasNext()){System.out.println(iterator.next());}}
好了,解析结束。
这是:自定义网络接口链接