工作中遇到一个问题,我们提供给外包方的 json 无法Decode 。
一段简单 JSON 字符串,字符串如下。
String json= "{\"0\":{\"id\":\"2\",\"category_id\":\"1\",\"title\":\"Test2\",\"author\":\"\",\"ctime\":\"2016-03-05 11:59:56\"},\"1\":{\"id\":\"1\",\"category_id\":\"1\",\"title\":\"Test1\",\"author\":\"\u6d4b\u8bd5\",\"ctime\":\"2016-03-05 11:57:30\"},\"pages\":{\"count\":2,\"first\":0,\"last\":0,\"before\":0,\"current\":0,\"next\":0,\"total\":0}}";
对方话费了大量时间解决不了问题。后来说请了 “新浪” 高手过来(让我想到周星驰电影,他们请来大内高手高手高高手)。看后也无能为力,说我们JSON 字符串不符合JSON标准规范。
我无语!啥也不说了,帮你们写一个例子吧。
https://github.com/google/gson
首先看看怎么剥离一层Map
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sender</groupId>
<artifactId>sender</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Sender</name>
<description>EDM</description>
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
package io.github.netkiller;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.*;
public class GsonTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Gson gson = new Gson();
String json = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
Map<String, String> map = new HashMap<String, String>();
map = (Map<String, String>) gson.fromJson(json, map.getClass());
System.out.println(map.get("k1"));
}
}
Gson gson = new Gson();
String json= "{\"0\":{\"id\":\"2\",\"category_id\":\"1\",\"title\":\"Test2\",\"author\":\"\",\"ctime\":\"2016-03-05 11:59:56\"},\"1\":{\"id\":\"1\",\"category_id\":\"1\",\"title\":\"Test1\",\"author\":\"\u6d4b\u8bd5\",\"ctime\":\"2016-03-05 11:57:30\"},\"pages\":{\"count\":2,\"first\":0,\"last\":0,\"before\":0,\"current\":0,\"next\":0,\"total\":0}}";
Map<String, Map> map = new HashMap<String, Map>();
map = (Map<String, Map>) gson.fromJson(json, map.getClass());
System.out.println(map.get("1").get("title"));
System.out.println(map.get("pages").get("count"));
以上例子节选自 《Netkiller Java 手札》
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有