如何在 JAVA 中忽略 NullNode for deserialization JSON

所以问题是下一个:我有POJO,比如:


@Data

@Accessors(chain = true)

@JsonInclude(Include.NON_NULL)

public class TestPOJO {


  private Long id;

  private String name;

  private JsonNode jsonNode;

我也有json喜欢


{

   "id":1

   "name": "foo"

   "jsonNode":null

}

当我尝试反序列化最后一个


ObjectMapper objectMapper = new ObjectMapper();

TestPOJO testPojo = objectMapper.readValue(<json String>, TestPOJO.class);

我在字段所在的位置获取对象,但我需要在如何修复它?testPojojsonNodeNullNodetestPojo == null


HUX布斯
浏览 130回答 1
1回答

慕森卡

添加一个扩展的类,如果为 null,则返回 null:JsonDeserializer<JsonNode>parser.getText()import com.fasterxml.jackson.core.JsonParser;import com.fasterxml.jackson.databind.DeserializationContext;import com.fasterxml.jackson.databind.JsonDeserializer;import com.fasterxml.jackson.databind.JsonNode;import java.io.IOException;public class JsonNodeDeserializer extends JsonDeserializer<JsonNode> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public JsonNode deserialize(JsonParser parser, DeserializationContext context)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throws IOException {&nbsp; &nbsp; &nbsp; &nbsp; String value = parser.getText();&nbsp; &nbsp; &nbsp; &nbsp; if(value == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return (JsonNode) context.findRootValueDeserializer(context.constructType(JsonNode.class)).deserialize(parser, context);&nbsp; &nbsp; }}然后对属性进行注释,以告诉 Jackson 使用您的自定义反序列化程序:jsonNode@JsonDeserialize(using = JsonNodeDeserializer.class)@Data@Accessors(chain = true)@JsonInclude(Include.NON_NULL)public class TestPOJO {&nbsp; private Long id;&nbsp; private String name;&nbsp; @JsonDeserialize(using = JsonNodeDeserializer.class)&nbsp; private JsonNode jsonNode;&nbsp; // getters and setters}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java