json link

The whole problem is chapters. in fact, it is a cod of such things that should be added to the array. But what is there is. How do I do this Json in Pojo (Gson). Thus, the chapters in an array, and not as 5 separate objects. Since they are always dynamic.

And I want to use this model for all requests of this type.

I know that you need to add chapters to the List<> or HashMap

1 answer 1

You can write your JsonDeserializer<Chapter[]> , which will read json in Map<String, Chapter> (where Chapter is the class representing the chapter) and then convert this Map to Chapter[] (using the Map::values and Collection::toArray methods Collection::toArray ).

For example, if json looks like this:

 { "chapters": { "5767ab95-8ab0-490b-8c08-cd4963567f75": { "title": "Welcome" }, "2eec0125-1613-4ed7-81b5-c10b55ba3e3d": { "title": "Understanding the Rules of the Game" }, "21e66272-76bc-4586-a02f-c64bdaad9d4f": { "title": "Understanding Personality " } } } 

you can write this code:

 static class Chapter { String title; // остальные поля } static class Data { Chapter[] chapters; // остальные поля } static class ChapterArrayAdapter implements JsonDeserializer<Chapter[]> { @Override public Chapter[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // получаем тип для Map<String, Chapter> Type mapType = new TypeToken<Map<String, Chapter>>() {}.getType(); // десериализуем Map<String, Chapter> Map<String, Chapter> map = context.deserialize(json, mapType); // преобразуем в массив return map.values().toArray(new Chapter[0]); } } public static void main(String[] args) throws Exception { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Chapter[].class, new ChapterArrayAdapter()); Gson gson = builder.create(); Data data = gson.fromJson(new FileReader("data.json"), Data.class); }