最近在做的项目涉及到把json数据格式转换成list集合的需求,在网上看了一些文章,但是觉得比较凌乱,现在问题已经解决,特此写下此文章记录一下。
1.添加相关依赖
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
2.我们处理的json格式是如下所示:
{
"info": [
{
"topoName": "mtd_recommend_dev_netty_n002",
"weight": 50
},
{
"topoName": "mtd_recommend_dev_netty_n001",
"weight": 100
}
]
}
3.具体代码实现如下:
String result=HttpRequest.sendGet(zooUrl+"gettopo",param);
System.out.println("result--"+result);
JSONObject obj=JSONObject.parseObject(result);//获取jsonobject对象
System.out.println("obj---"+obj);
JSONArray arr=obj.getJSONArray("info");//获取的结果集合转换成数组
System.out.println("arr---"+arr);
List list1=new ArrayList();
for(int i=0;i<arr.size();i++){
Map map=new HashMap();
Map omap=(Map) arr.get(i);
System.out.println("omap--"+omap);
String value1=(String) omap.get("topoName");
System.out.println("value1--"+value1);
Integer value2=(Integer)omap.get("weight");
System.out.println("value2--"+value2);
map.put("weight",value1);
map.put("count",value2);
list1.add(map);
}
result就是我取到的上述json值
这就是我的实现过程,可以最终得到list集合
可以在自己的代码中去debug调试,看看是怎么一步步处理json数据的
新手,对于json并不是很了解,只是需求实现了,如有错误,欢迎指正