我有json:
{
"albums": [
{
"default": {
"privacy": "public"
......
}
}
},
{
"second_album": {
"privacy": "public"
......
}
},
{
"third_album": {
"privacy": "public"
......
}
}
}
]
}
我想为这个json制作Java对象。
public class AlbumsResponse {
private List<Album> albums = new ArrayList<>();
public List<Album> getAlbums() {
return albums;
}
public void setAlbums(List<Album> albums) {
this.albums = albums;
}
}
和
public class Album {
private Title title;
public Title getTitle() {
return title;
}
public void setTitle(Title title) {
this.title = title;
}
}
但正如你所看到的,Album没有任何&#34; Title&#34; json中的字段,但有这样的东西
"second_album": {
"privacy": "public"
......
}
如何使用它?如何将json-object的名称作为json-array中的单位转换为字段&#34; title&#34;在java-object?
答案 0 :(得分:0)
根据您的问题,我不完全确定您希望如何将显示的对象转换为Title
,但我相信您可以使用custom deserializer来实现您所寻找的目标。< / p>
例如,以下反序列化器获取JSON对象的第一个键,将其包含在Title
中,然后返回Album
Title
:
public static class AlbumDeserializer implements JsonDeserializer<Album> {
@Override
public Album deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// Get the key of the first entry of the JSON object
JsonObject jsonObject = json.getAsJsonObject();
Map.Entry<String, JsonElement> firstEntry = jsonObject.entrySet().iterator().next();
String firstEntryKey = firstEntry.getKey();
// Create a Title instance using this key as the title
Title title = new Title();
title.setTitle(firstEntryKey);
// Create an Album instance using this Title
Album album = new Album();
album.setTitle(title);
return album;
}
}
然后,您可以使用Gson
实例注册此自定义反序列化器,并使用它转换JSON:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Album.class, new AlbumDeserializer())
.create();
AlbumsResponse response = gson.fromJson(json, AlbumsResponse.class);
System.out.println(response);
假设您的类以基本方式实现toString
,使用您的示例运行此命令将打印以下内容:
AlbumsResponse{albums=[Album{title=Title{title='default'}}, Album{title=Title{title='second_album'}}, Album{title=Title{title='third_album'}}]}