Skip to content Skip to sidebar Skip to footer

Java Parse Json With Array With Different Object Types (gson Or Jackson Or Etc.)

{ 'response': { 'data': { '333': [ { 'id': '69238', 'code': '545' }, { 'id': '69239', 'code':

Solution 1:

You can use a custom deserializer. The below example is using Gson, but the same thing can be done with Jackson.

classCustomDeserializerimplementsJsonDeserializer<Response> {

    @OverridepublicResponse deserialize(JsonElement jsonElement, Type typeOfElement, JsonDeserializationContext context) throwsJsonParseException {
        JsonObject data = jsonElement.getAsJsonObject().get("response").getAsJsonObject().get("data").getAsJsonObject();
        Type listType = new TypeToken<List<Data>>() {}.getType();
        Map<String, List<Data>> dataMap = new HashMap<String, List<Data>>();

        for (Map.Entry<String, JsonElement> entry : data.entrySet()) {
            List<Data> dataList = context.deserialize(entry.getValue(), listType);

            dataMap.put(entry.getKey(), dataList);
        }

        return new Response(dataMap);
    }
}

In the main class:

String json = "...";

Gson gson = new GsonBuilder().registerTypeAdapter(Response.class, new CustomDeserializer()).create();

System.out.println(gson.fromJson(json, Response.class));

Class for the response:

classResponse{
    private Map<String, List<Data>> data;

    public Response(Map<String, List<Data>> data) {
        this.data = data;
    }
}

Class for each data object:

classData{
    privateString id;
    privateString code;
    privateString mark;
}

The response here will have a map of each data entry and a list of its values. (ex: 333 -> list of Data objects), but you can change the deserializer to have the key (333) to be one of the variables of the Data object and assign it in the for loop.

Post a Comment for "Java Parse Json With Array With Different Object Types (gson Or Jackson Or Etc.)"