gpt4 book ai didi

java - jackson 忽略了特定的属性(property),但能够检查它是否可用

转载 作者:行者123 更新时间:2023-11-30 01:42:55 24 4
gpt4 key购买 nike

有没有办法在反序列化时跳过某些属性,但同时知道它们是否存在?

{
"id": 123,
"name": "My Name",
"picture": {
// a lot of properties that's not important for me
}
}
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
private int id;
}

因此,我 ignoreUnknown 是我想要的默认行为,因为我不想要 name 字段以及所有其他可能存在的字段。 picture 字段的值也不重要。我只是想知道 picture 属性是否可用。我怎样才能做到这一点?

最佳答案

您可以添加一个 boolean 属性和自定义反序列化器,它只读取给定值并返回 true。仅当有效负载中存在属性时,Jackson 才会调用自定义反序列化器。

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.io.File;
import java.io.IOException;

public class JsonApp {

public static void main(String[] args) throws Exception {
File jsonFile = new File("./src/main/resources/test.json");
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(jsonFile, User.class));
}
}

class PropertyExistsJsonDeserializer extends JsonDeserializer<Boolean> {
@Override
public Boolean deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
p.readValueAsTree(); //consume value
return Boolean.TRUE;
}
}

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
class User {
private int id;

@JsonDeserialize(using = PropertyExistsJsonDeserializer.class)
@JsonProperty("picture")
private boolean pictureAvailable;

//getters, setters, toString
}

上面的代码打印:

User{id=123, pictureAvailable=true}

关于java - jackson 忽略了特定的属性(property),但能够检查它是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59301619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com