通过 GSON 序列化 ArrayList <HashMap>

Serialize ArrayList <HashMap> via GSON

我有以下代码:

ArrayList<HashMap<String,String>> arr = new ArrayList<HashMap<String,String>>();
arr.add(new HashMap<String, String>(){{
        put("title","123");
        put("link","456");
}});
print(arr.toString());
print(new Gson().toJson(arr));

我得到以下输出:

[{link=456, title=123}]
[null]

但我希望是:

[{link=456, title=123}]
[{"title":"123","link":"456"}] //Serialize ArrayList<HashMap> via GSON

找了很多帖子,都不知道。 感谢您的回复。

请尝试我有的其他解决方案。

  1. 第一个仅使用 Gson 包中的 JsonObjectJsonArray
private static void toJsonElement(String title, String link) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("title", title);
        jsonObject.addProperty("link", link);
        JsonArray jsonArray = new JsonArray();
        jsonArray.add(jsonObject);
        System.out.println(jsonArray);
}
  1. JsonObjectArrayList
  2. 结合使用
private static void toArrayList(String title, String link) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("title", title);
        jsonObject.addProperty("link", link);
        List<JsonObject> listOfObject = new ArrayList<>();
        listOfObject.add(jsonObject);
        System.out.println(new Gson().toJson(listOfObject)); // listOfObject.toString() also works
}

使用TypeToken获取类型

Gson uses Java reflection API to get the type of the object to which a Json text is to be mapped. But with generics, this information is lost during serialization. To counter this problem, Gson provides a class com.google.gson.reflect.TypeToken to store the type of the generic object.

例如:

ArrayList<HashMap<String, String>> arr = new ArrayList<>();
arr.add(new HashMap<String, String>() {{
    put("title", "123");
    put("link", "456");
}});
System.out.println(arr.toString());

Type type = new TypeToken<ArrayList<HashMap<String, String>>>() {}.getType();
System.out.println(new Gson().toJson(arr, type));

输出:

[{link=456, title=123}]
[{"link":"456","title":"123"}]