0

I have the json:

{
  "albums": [
    {
      "default": {
        "privacy": "public"
           ......
        }
      }
    },
    {
      "second_album": {
        "privacy": "public"
        ......
      }
    },
    {
      "third_album": {
        "privacy": "public"
        ......
      }
    }
  }
  ]
}

I want to make Java Objects for this json.

public class AlbumsResponse {

     private List<Album> albums = new ArrayList<>();

     public List<Album> getAlbums() {
         return albums;
     }

     public void setAlbums(List<Album> albums) {
         this.albums = albums;
     }
}

and

public class Album {

    private Title title;

    public Title getTitle() {
        return title;
    }

    public void setTitle(Title title) {
        this.title = title;
    }

}

But as you can see Album has no any "Title" field in json but has something like this

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

How to work with this? How to convert name of json-object as unit in json-array to field "title" in java-object?

Yura Buyaroff
  • 1,718
  • 3
  • 18
  • 31

1 Answers1

0

Based on your question, I am not entirely sure how you want to convert the object shown into a Title, but I believe that you can achieve what you are looking for with a custom deserializer.

For example, the following deserializer takes the first key of the JSON object, wraps this in a Title, and then returns an Album with that 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;
    }
}

You can then register this custom deserializer with your Gson instance, and convert your JSON with it:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(Album.class, new AlbumDeserializer())
        .create();

AlbumsResponse response = gson.fromJson(json, AlbumsResponse.class);

System.out.println(response);

Assuming that your classes implement toString in a basic way, running this with your example prints the following:

AlbumsResponse{albums=[Album{title=Title{title='default'}}, Album{title=Title{title='second_album'}}, Album{title=Title{title='third_album'}}]}
andersschuller
  • 13,509
  • 2
  • 42
  • 33