【问题标题】:What is wrong with my JSON string?我的 JSON 字符串有什么问题?
【发布时间】:2014-07-15 22:38:08
【问题描述】:

我认为我使用的 JSON 字符串运行良好。我偶然发现了我的单元测试,发现我的 JSON 使用 google 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

【问题讨论】:

  • json 字符串对我来说看起来不错。 json数据没有错。
  • 您的代码对我有用。我得到 JSON 是 {"hybrid":"true","trimName":"act"} JSON 是 "true" json 字符串没有问题。
  • 可能是类路径问题?尝试以最少的依赖项运行它,然后看看它是否有效。也许你有一个冲突的 JsonObject 类。

标签: java json gson


【解决方案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

您可以使用TypeTokenType 将JSON 字符串转换为Map<String, String>

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

【讨论】:

    猜你喜欢
    • 2015-12-04
    • 2016-01-20
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    相关资源
    最近更新 更多