杰克逊在通用名单中读了json [英] Jackson read json in generic List

查看:139
本文介绍了杰克逊在通用名单中读了json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用杰克逊来阅读json消息。我试图解析的一个值是List,另一个值包含列表中数据的类型。这是我在java中创建的结构。

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 the structure i 've created in java.

public class Message<T> {
   private Timestamp time;
   private RestAction action;
   private String type;
   private List<T> data;
}

通过 Class.forName(); 我可以得到代表列表中数据的类。问题是如何阅读清单。

Through Class.forName(); I can get the class which represents the data in the list. The question is how can I read the List.

推荐答案

如果你需要将传入的json映射到你的List你可以这样做

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 <T> result = mapper.readValue(jsonString, type);

修改

类似这样,完全未经测试且从未完成

Something like this, completly untested and never done

public Message<T> 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 <T> data = mapper.readValue(list, listType);

    Message<T> message = new Message<T>;
    message.setTime(time);
    message.setAction(action);
    message.setType(type);
    message.setData(data);

    return message;
}

这篇关于杰克逊在通用名单中读了json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆