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;
}

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映射到您的列表,可以这样做

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);

Edit

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相关问答推荐

如何获取brew list作为JSON输出

将 REST API - json 输出转换为表 Power BI

Rust实现:高效解析任意大小的JSON数组

如何使用 jq 在连续的 json 记录流上调用操作

VBA-JSON 嵌套集合解析为 Excel

Jolt 变换 - 如何用字段值重命名字段?

从 PySpark 中的复杂 JSON 文件中高效清除 HTML 实体

杰克逊 2.0 和 Spring 3.1

Jackson 的@JsonView、@JsonFilter 和 Spring

消息通知产生此内容无法显示

Spring MVC:不反序列化 JSON 请求正文

如何创建 JSON 对象 Node.js

如何使用 Newtonsoft.Json 包在 C#(4.0) 中解析我的 json 字符串?

为不同类型的项目数组正确的 JSON Schema

杰克逊:反序列化 for each 值都具有正确类型的 Map

Jackson JSON序列化,通过级别定义避免递归

如何在 Python 中合并两个 json 字符串?

无法将空值放入 JSON 对象

python追加到json对象中的数组

为什么 jqXHR.responseText 返回字符串而不是 JSON 对象?