Jackson read json in generic List

后端 未结 4 783
旧时难觅i
旧时难觅i 2020-12-24 13:36

I\'m using Jackson in order to read json messages. One of the values that I\' trying to parse is a List and another value contains the type of the data in the list. This is

4条回答
  •  借酒劲吻你
    2020-12-24 13:41

    If you need to map the incoming json to your List you can do like this

    String jsonString = ...; //Your incoming json string
    ObjectMapper mapper = new ObjectMapper();
    Class clz = Class.forName(yourTypeString);
    JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, clz);
    List  result = mapper.readValue(jsonString, type);
    

    Edit

    Something like this, completly untested and never done

    public Message deserialize(JsonParser jsonParser, DeserializationContext arg1)
        throws IOException, JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
    
        JsonNode timeStamp = node.get("time");
        Timestamp time = mapper.readValue(timeStamp, Timestamp.class);
        JsonNode restAction = node.get("action");
        RestAction action = mapper.readValue(restAction, RestAction.class);
        String type = node.get("type").getTextValue();
        Class clz = Class.forName(type);
        JsonNode list = node.get("data");
        JavaType listType = mapper.getTypeFactory().constructCollectionType(List.class,   clz);
        List  data = mapper.readValue(list, listType);
    
        Message message = new Message;
        message.setTime(time);
        message.setAction(action);
        message.setType(type);
        message.setData(data);
    
        return message;
    }
    

提交回复
热议问题