Jackson读取泛型列表中json

vnjpjtjt  于 2022-11-08  发布在  其他
关注(0)|答案(6)|浏览(186)

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

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

通过Class.forName();可以得到表示列表中数据的类,问题是如何读取List。

dced5bon

dced5bon1#

如果你需要把传入的jsonMap到你的List,你可以这样做

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

编辑

像这样的东西,完全未经测试,从来没有做过

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

fjaof16o2#

您需要使用@JsonDeserialize(using = MessageDeserializer.class)对类进行注解,并实现自定义反序列化器:

public class MessageDeserializer extends JsonDeserializer<Message> {
  @Override
  public Message deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
    throws IOException, JsonProcessingException {
    // YOU DESERIALIZER CODE HERE
  }
}

@请参见此处的示例:How Do I Write a Jackson JSON Serializer & Deserializer?

kyxcudwk

kyxcudwk3#

自版本2.11(2020年4月)起,Jackson拥有readerForListOf方法(文档):

ObjectMapper mapper = ObjectMapper().configure(...);
ObjectReader reader = mapper.readerForListOf(MyClass.class);
List<MyClass> list = reader.readValue(...);
kupeojn6

kupeojn64#

这应该适用于简单的POJO和集合:

// import com.fasterxml.jackson.core.type.TypeReference;
// import com.fasterxml.jackson.databind.ObjectMapper;

// get your <T> type
final Type entryType = ...

// Create a new TypeReference object and convert
return new ObjectMapper().readValue(jsonString, new TypeReference<>() {
    @Override
    public Type getType() {
        return entryType;
    }
});
uoifb46i

uoifb46i5#

如果您需要读取泛型List中的json,请执行以下操作

{
    Employee:
    [
        {
            "key": "value",
            "key": "value"
        },
        {
            "key": "value",
            "key": "value"
        }
    ]
}

您json列表对象和bean类

class person {
private String key;
private String value;
}

现在您可以使用HashMap读取这个json
类似于

TypeReference<HashMap<String,List<Person>>> personList =  new   TypeReference<HashMap<String, List<Person>>>() {};

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

HashMap<String, List<Person>> employees = objectMapper.readValue(request.getInputStream(), personList);
shyt4zoc

shyt4zoc6#

短得多的东西:

mapper.readValue(jsonString, new TypeReference<List<EntryType>>() {});

其中,EntryType是对要在集合中保留的类型的引用。它可以是任何Java类。例如,要读取JSON表示形式(如["a", "b", "c"]),Map器的第二个参数应为new TypeReference<List<String>>() {}

相关问题