【问题标题】:JSON to hashmap with GSONJSON 到带有 GSON 的 hashmap
【发布时间】:2014-02-12 20:43:18
【问题描述】:

我正在使用 Java 进行一个项目,我想使用 GSON 将文本放入 HashMap,这是我的 JSON:

{
"someText": {
    "text1": "lorem ipsum",
    "text2": "ipsum lorem"
    }
}

这是我的一段代码:

private static class myTexts {
    private final Map<String, String> someText = new HashMap<String, String>();
}  

myTexts t = this.gson.fromJson(myJsonFile, myTexts.class);

我有这个错误:com.google.gson.JsonSyntaxException: duplicate key: null,我已经尝试了一段时间,但我似乎无法找到问题:/

【问题讨论】:

  • 最后我忘记了“}”。这是我真正的 Json,我刚刚完成了复制和粘贴错误。

标签: java json map hashmap gson


【解决方案1】:

如果你添加一个结束 }

{
"someText": {
    "text1": "lorem ipsum",
    "text2": "ipsum lorem"
}}
 ^

从而使您的 JSON 格式良好,如下

myTexts t = new Gson().fromJson(myJsonFile, myTexts.class);
System.out.println(t.someText);

打印

{text1=lorem ipsum, text2=ipsum lorem}

这似乎是你所期待的。

【讨论】:

    【解决方案2】:

    试试这个!

    public static Map<String, String> jsonToMap(String jsonString) {
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Gson gson = new Gson();
        return gson.fromJson(jsonString, type);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 2011-07-12
      • 1970-01-01
      • 2014-04-26
      相关资源
      最近更新 更多