获取JSON格式的字符串各个属性对应的值
{"lastrdtime":1515998187379,"creditbalance":"$5.00","contactmode":"0100000003","consname":"100000030060","consno":"100000030060","consaddr":"北京市海淀区中关村","lastreading":"125.00"}
现在有上面JSON格式的字符串, 如何获取consno对应的值100000030060?
==方式一:Google的Gson.================================================
1.基于maven,导入谷歌的Gson包:
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.2</version> </dependency>
2.创建Gson对象, 将JSON字符串转为Map对象, Map取值就哦了.(转成自定义的javaBean, 通过getXxx()取值也可以)
Gson gson = new Gson(); Map map = gson.fromJson(stringEntity, Map.class);
System.out.println(map.get("consno"));
结果:
100000030060
==方式二:阿里的FastJson.================================================
1.基于maven, 导入阿里的FastJson包:
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.41</version> </dependency>
2.调用JSON类的parseObject方法, 将字符串转为JSONObject:
JSONObject jsonObject = JSON.parseObject(jsonEntity); System.out.println(jsonObject.get("consno"));
结果:
100000030060
附:
package com.test.com.pers.others; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.gson.Gson; import java.util.Map; /** * Created by yadongliang on 2018/1/15 0015. */ public class GetJsonParameter { public static void main(String[] args) { String stringEntity = "{'consno':'100000030060','consaddr':'北京市海淀区中关村'}"; /** * 方式一:Google的Gson. */ Gson gson = new Gson(); Map map = gson.fromJson(stringEntity, Map.class); System.out.println(map.get("consno")); System.out.println(map.get("consaddr")); /** * 方式二:阿里的FastJson. */ JSONObject jsonObject = JSON.parseObject(stringEntity); System.out.println(jsonObject.get("consno")); System.out.println(jsonObject.get("consaddr")); System.out.println(jsonObject.getString("consno")); System.out.println(jsonObject.getString("consaddr")); } }
另, 可参考另一篇:FastJson对于JSON格式字符串、JSON对象及JavaBean之间的相互转换
这篇讲的更细致...
作者:习惯沉淀
如果文中有误或对本文有不同的见解,欢迎在评论区留言。
如果觉得文章对你有帮助,请点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
扫码关注一线码农的学习见闻与思考。
回复"大数据","微服务","架构师","面试总结",获取更多学习资源!