获取JSON格式的字符串各个属性对应的值

时间:2023-03-08 17:32:13
{"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之间的相互转换

这篇讲的更细致...