Java Parse Json with array with different object types (Gson or Jackson or etc.)

后端 未结 1 1708
猫巷女王i
猫巷女王i 2021-01-27 00:51
 {
   \"response\": {
     \"data\": {
       \"333\": [
         {
           \"id\": \"69238\",
           \"code\": \"545\"
         },
         {
           \"id\":          


        
相关标签:
1条回答
  • 2021-01-27 01:24

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

    class CustomDeserializer implements JsonDeserializer<Response> {
    
        @Override
        public Response deserialize(JsonElement jsonElement, Type typeOfElement, JsonDeserializationContext context) throws JsonParseException {
            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:

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

    Class for each data object:

    class Data {
        private String id;
        private String code;
        private String 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.

    0 讨论(0)
提交回复
热议问题