【问题标题】:Mapping Json Array with Objects as String names (Java)将对象映射为字符串名称的 Json 数组 (Java)
【发布时间】:2016-05-31 08:00:40
【问题描述】:

我有 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;
    }

}

但正如您所见,专辑在 json 中没有任何“标题”字段,但有类似这样的内容

  "second_album": {
    "privacy": "public"
    ......
  }

如何使用它?如何将json-object的名称作为json-array中的单位转换为java-object中的字段“title”?

【问题讨论】:

标签: java json mapping gson pojo


【解决方案1】:

根据您的问题,我不完全确定您希望如何将显示的对象转换为 Title,但我相信您可以使用 custom deserializer 实现您想要的。

例如,以下反序列化程序获取 JSON 对象的第一个键,将其包装在 Title 中,然后返回带有 TitleAlbum

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'}}]}

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    相关资源
    最近更新 更多