[英]Convert complex Java object to Json using Gson
我正在使用GSON序列化Java对象。
我有一个具有以下属性的Java类。
String property1;
Map<String, HashMap> property2 = new HashMap<>();
Map<String, ArrayList<String>> property3 = new HashMap<>();
Map<String, String[]> property4 = new HashMap<>();
我想将其转换为Json。 由于内部带有HashMaps的地图,因此变得很困难。 我知道我可以通过gsonObject.toJson(map)
获得地图的Json。 但是我想要Json Object中的所有这些属性。 (合而为一。不连接许多对象)
谁能帮助我完成这项工作?
我看不出问题是什么。 Gson可以序列化Map
。
假设您的班级名为Test
Test test = new Test();
test.property1 = "some value";
HashMap<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("fourty two", 42);
test.property2.put("property2-key", map);
ArrayList<String> strings = new ArrayList<>(Arrays.asList("string1",
"string2", "string3"));
test.property3.put("property3-key", strings);
String[] stringArray = { "array1", "array2", "array3" };
test.property4.put("property4-key", stringArray);
Gson gson = new Gson();
String json = gson.toJson(test);
System.out.println(json);
它产生以下
{
"property1": "some value",
"property2": {
"property2-key": {
"fourty two": 42,
"one": 1
}
},
"property3": {
"property3-key": [
"string1",
"string2",
"string3"
]
},
"property4": {
"property4-key": [
"array1",
"array2",
"array3"
]
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.