我的JSON字符串有什么问题?

时间:2014-05-27 06:15:03

标签: java json gson

我认为我所拥有的JSON字符串工作正常。我偶然发现了我的单元测试,发现使用google JSON库进行的Gson解析不再有效了。有没有人知道为什么这不起作用?

String json = "{\"hybrid\":\"true\",\"trimName\":\"act\"}";
JsonObject data = new Gson().fromJson(json, JsonObject.class);
System.out.println(" JSON is  "+data);
System.out.println(" JSON is  "+data.get("hybrid"));

我得到的输出是

 JSON is  {}
 is hybrid ?  null

1 个答案:

答案 0 :(得分:1)

解决方案1 ​​

JsonObject中的解决方案以及使用JsonParser将JSON字符串直接转换为JsonObject而不使用Gson

JsonParser parser = new JsonParser();
JsonObject jsonObject = (JsonObject) parser.parse(json);

System.out.println(" JSON is  " + jsonObject);
System.out.println(" JSON is  " + jsonObject.get("hybrid"));

输出:

 JSON is  {"hybrid":"true","trimName":"act"}
 JSON is  "true"

解决方案2

您可以使用Map<String, String>TypeToken

将JSON字符串转换为Type
String json = "{\"hybrid\":\"true\",\"trimName\":\"act\"}";
Type type = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> data = new Gson().fromJson(json, type);

System.out.println(" JSON is  " + data);
System.out.println(" JSON is  " + data.get("hybrid"));

输出:

 JSON is  {hybrid=true, trimName=act}
 JSON is  true
相关问题