springboot处理fastjson的多层嵌套
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot处理fastjson的多层嵌套相关的知识,希望对你有一定的参考价值。
我要获取json的信息,但是问题是json嵌套了太多层,刚开始我想到阿里巴巴的fastjson工具
导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
json的层次图如下
@RestController
@Slf4j
public class Song_infoController
@RequestMapping("/songinfo")
public void save(@PathVariable("id") long id) throws IOException
String ur = "http://localhost:3000/user/record?";
URI uri = URI.create(ur);
URL url = uri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.POST.name());
connection.setDoOutput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//System.out.println(reader.readLine());
JSONArray list = new JSONArray();
//list = JSONArray.parseArray(reader.toString());
JSONObject jsonObject=JSONObject.parseObject(reader.readLine());
// String code = jsonObject.getString("weekData");
// System.out.println(code);
list = jsonObject.getJSONArray("weekData");
// 遍历JSONArray
for (Iterator<Object> iterator = list.iterator(); iterator.hasNext(); )
JSONObject next = (JSONObject) iterator.next();
//System.err.println("a ===>>> " + next.getString("song"));
String songinfo = next.getString("song");
Integer playCount = next.getInteger("playCount");
Integer score = next.getInteger("score");
JSONObject jsonObject1=JSONObject.parseObject(songinfo);
String name= jsonObject1.getString("name");
System.out.println("************"+name);
Integer songid = jsonObject.getInteger("id");
String ar= jsonObject1.getString("ar");
System.out.println("************"+ar);
JSONArray jsonArray=JSONArray.parseArray(ar);
System.out.println(jsonArray.getString(0));
//String artis = jsonObject2.getString("name");
//System.out.println("a========>"+artis+"=="+songid);
String line= jsonArray.getString(0);
JSONObject jsonObject2=JSONObject.parseObject(line);
System.out.println(jsonObject2.getString("name"));
fastjson里面有一个叫JSONObject和JSONArray,两者的区别是一个是json对象和一个是json数组,但两者能识别的json还是有区别的
如JSONArray能识别外面带[],而jsonobject只能识别,如果不加对比会出现
com.alibaba.fastjson.JSONArray cannot be cast to com.alibaba.fastjson.JSONObject
的异常,因为两者是不同的结构
以上是关于springboot处理fastjson的多层嵌套的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot Fastjson解析多层嵌套复杂Json字符串
fastjson反序列化多层嵌套泛型类与java中的Type类型
Springboot中多层object嵌套转换类的处理方法?