我有课:
public class Profile {
private int name;
// getter and setter
}
和其他地方的这个方法:
public static void printProfiles(Profile[] profiles) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(profiles));
}
不出所料,我得到以下结果:
[
{
"name": "some name 1"
},
{
"name": "some name 2"
}
]
但我希望 Profile[] 数组被序列化为 JSON 对象而不是 JSON 数组,这样输出 JSON 中的每个配置文件都有一个分配给它的键,并且它们嵌套在 JSON 对象中的一个数组。像这样的东西:
{
"profile1": {
"name": "some name 1"
},
"profile2:" {
"name": "some name 2"
}
}
我将如何着手完成这个?我对 GSON 不是很熟悉,无法通过阅读文档找出解决方案。提前致谢!
我试过创建一个配置文件类:
public class Profiles {
private Profile profile1;
private Profile profile2;
// etc
// setters and getters
}
然后更新我的方法:
public static void printProfiles(Profiles profiles) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(profiles));
}
给出了预期的结果。但这显然不是真正的解决方案,因为配置文件的数量各不相同,可能有数百个。
您可以创建一个 Map,其中键是自定义键,值是对象。然后你可以使用 GSON 序列化地图。
public static void printProfiles(Profile[] profiles) {
Map<String, Profile> profileMap = new HashMap<>();
for (int i = 0; i < profiles.length; i++) {
profileMap.put("profile" + (i + 1), profiles[i]);
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(profileMap));
}