public static void main(String[] args) {
//json格式的字符串
String json = "{'source':'95','custelno':'','pasmid':'CBC8D8A800000001',"
+ "'userid':'','items':[{'skuo2oid':'','goodsid':22063,'skuid':34220,"
+ "'goodsname':'多力黄金三益5L/桶*4桶','goodscount':1,'channel':27}],'wholesale':'2B'}";
//目的:取json格式的字符串的值
//将其转化为某个具体的bean类,再取里面的属性值。
//1.fastjson[支持单引号]
CheckCouponInfo cci = JSON.parseObject(json, CheckCouponInfo.class);
System.out.println(cci.getSource());
//2.json-lib[支持单引号]
JSONObject jsonObject = JSONObject.fromObject(json);
CheckCouponInfo cci2 = (CheckCouponInfo) JSONObject.toBean(jsonObject, CheckCouponInfo.class);
System.out.println(cci2.getSource());
//3.json-mapper[不支持单引号,需要加一层配置]
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);//允许单引号
CheckCouponInfo cci3 = new CheckCouponInfo();
try {
cci3 = mapper.readValue(json, CheckCouponInfo.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(cci3.getSource());
//4.gson[支持单引号]
Gson gson = new Gson();
CheckCouponInfo cci4 = gson.fromJson(json, CheckCouponInfo.class);
System.out.println(cci4.getSource());
}
1.maven:gson的jar包依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
2.maven:fastjson的jar包依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.26</version>
</dependency>
3.ObjectMapper的jar包依赖【未求证】
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.2.2</version>
</dependency>
4maven:json-lib的jar包依赖
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<classifier>jdk15</classifier>
<version>2.3</version>
</dependency>
貌似还有其他的依赖,在我其他博客中有介绍。