jackson在通用名单中读了json
我正在使用jackson来阅读json消息。 我试图解析的一个值是List,另一个值包含列表中数据的类型。 这是我在java中创建的结构。
public class Message { private Timestamp time; private RestAction action; private String type; private List data; }
通过Class.forName();
我可以得到代表列表中数据的类。 问题是如何阅读清单。
如果你需要将传入的json映射到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 result = mapper.readValue(jsonString, type);
编辑
像这样的东西,完全未经测试,从未完成
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; }
更短的东西:
mapper.readValue(jsonString, new TypeReference>() {});
您需要使用@JsonDeserialize(using = MessageDeserializer.class)
注释您的类并实现自定义反序列化器:
public class MessageDeserializer extends JsonDeserializer { @Override public Message deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { // YOU DESERIALIZER CODE HERE } }
@see示例: 如何编写Jackson JSON Serializer和Deserializer?
如果你需要在通用列表中读取json,请执行类似的操作
{ Employee: [ { "key": "value", "key": "value" }, { "key": "value", "key": "value" } ] }
你的json list对象和你的bean类是
class person { private String key; private String value; }
现在你可以使用HashMap阅读这个json了
就像是
TypeReference>> personList = new TypeReference>>() {}; ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); HashMap> employees = objectMapper.readValue(request.getInputStream(), personList);
- Jackson ObjectMapper DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
- 在springboot反序列化器中包含带jackson的root对象
- 使用Jackson的JSON反序列化:没有为类型找到合适的构造函数 – 提供默认构造函数或注释构造函数是不可能的
- 当jackson反序列化失败时,Jerseyexception映射器无法正常工作
- jackson将额外的字段反序列化为地图
- 使用Jackson注释将子数组解析为JSON?
- 无法捕获JsonMappingException
- 如何使用基于java.util.Map的类序列化Jackson
- 如何使用Jackson和注释以不同方式序列化关联对象?