gpt4 book ai didi

java - 通过 GSON 序列化 ArrayList

转载 作者:行者123 更新时间:2023-12-01 16:52:51 24 4
gpt4 key购买 nike

我有以下代码:

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

查了很多帖子,还是不知道。感谢您的回复。

最佳答案

使用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"}]

关于java - 通过 GSON 序列化 ArrayList <HashMap>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61655920/

24 4 0