gpt4 book ai didi

java - 如何将 java.util.Optional 与 REST API 一起使用?

转载 作者:行者123 更新时间:2023-12-01 06:06:08 24 4
gpt4 key购买 nike

我有一个看起来像的类(class)

public class ActiveDirectorySetup implements Serializable {
private ActiveDirectoryDataSource activeDirectoryDataSource;
private Optional<ShActiveDirectorySettings> shActiveDirectorySettings;
private Optional<SaActiveDirectorySettings> saActiveDirectorySettings;
// ...
}

我通过 API 将其发送为
      Optional<ActiveDirectoryConfiguration> configuration = store.getConfiguration();
if (configuration.isPresent()) {
return configuration.get();
}

我在浏览器上看到的是
[
{
"activeDirectoryDataSource":{
"host":"localhost",
"port":0,
"userName":"user",
"password":"password",
"activeDirectoryQueryConfig":{
"base":{
"present":false
},
"filter":"filter",
"attributes":[

]
},
"activeDirectorySslSettings":{
"present":false
}
},
"shActiveDirectorySettings":{
"present":true
},
"saActiveDirectorySettings":{
"present":true
}
}
]

对于看起来像的有效载荷
{
"activeDirectorySetups": [
{
"activeDirectoryDataSource": {
"host": "localhost",
"port": 0,
"userName": "user",
"password": "password",
"activeDirectoryQueryConfig": {
"base": null,
"filter": "filter",
"attributes": []
},
"activeDirectorySslSettings": null
},
"shActiveDirectorySettings": {
"enableUserMapping": true,
"attributes": null
},
"saActiveDirectorySettings": null
}
]
}

如你所见,我得到 {"present":true}而不是实际值。

我正在使用 jackson-datatype-jdk8对于这项工作。我怎样才能强制它替换 {"present":true}与实际值 - 要么 null或者 {"enableUserMapping": true, "attributes": null}

最佳答案

我很确定您需要为此编写自定义序列化/反序列化功能。

解串器

public class OptionalDeserializer<T> extends StdDeserializer<Optional<T>> {

private ObjectMapper customObjectMapper;

private Class<T> type;

/**
* @param customObjectMapper any ObjectMapper, possibly with deserialization logic for the wrapped type
* @param type the wrapped type
*/
public OptionalDeserializer(ObjectMapper customObjectMapper, Class<T> type) {
this(Optional.class);
this.customObjectMapper = customObjectMapper;
this.type = type;
}

// At least one type-based constructor is required by Jackson
private OptionalDeserializer(Class<?> vc) {
super(vc);
}

@Override
public Optional<T> deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException {
// Read entire tree
JsonNode treeNode = jsonParser.getCodec().readTree(jsonParser);

// Check if "present" is true
if (treeNode.has("present") && treeNode.get("present").asBoolean()) {
// Read your wrapped value
return Optional.of(customObjectMapper.treeToValue(treeNode.get("data"), type));
}

// Return empty() by default
return Optional.empty();
}
}

序列化器

请注意,您可以包含自定义 ObjectMapperBox在管道中的任何位置键入。为简单起见,在序列化程序中省略了它。

public class OptionalSerializer<T> extends StdSerializer<Optional<T>> {

public OptionalSerializer(Class<T> type) {
this(TypeFactory.defaultInstance().constructParametricType(Optional.class, type));
}

protected OptionalSerializer(JavaType javaType) {
super(javaType);
}

@Override
public void serialize(Optional<T> value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeStartObject();
if (value.isPresent()) {
gen.writeBooleanField("present", true);
gen.writeObjectField("data", value.get());
} else {
gen.writeBooleanField("present", false);
}
gen.writeEndObject();
}
}

用法示例:

public static void main(String[] args) throws IOException {
ObjectMapper optionalMapper = new ObjectMapper();

SimpleModule module = new SimpleModule();
// Add any custom deserialization logic for Box objects to this mapper
ObjectMapper boxMapper = new ObjectMapper();
OptionalDeserializer<Box> boxOptionalDeserializer = new OptionalDeserializer<>(boxMapper, Box.class);
OptionalSerializer<Box> boxOptionalSerializer = new OptionalSerializer<>(Box.class);
module.addDeserializer(Optional.class, boxOptionalDeserializer);
// use addSerializer(JsonSerializer<?> ser), not addSerializer(Class<? extends T> type, JsonSerializer<T> ser)
// The generic types involved here will otherwise not let the program compile
module.addSerializer(boxOptionalSerializer);
optionalMapper.registerModule(module);

String json = "{\"present\": true, \"data\": {\"myValue\": 123}}";
Optional optional = optionalMapper.readValue(json, Optional.class);

@SuppressWarnings("unchecked") // Guaranteed safe cast
Optional<Box> boxOptional = (Optional<Box>) optional;

// Prints "123"
boxOptional.ifPresent(box -> System.out.println(box.getMyValue()));

// Prints the contents of "json" (variable defined above)
System.out.println(optionalMapper.writeValueAsString(boxOptional));
}

哪里 Box只是一个简单的示例类:

private static class Box {
private int myValue;

public int getMyValue() {
return myValue;
}

public void setMyValue(int myValue) {
this.myValue = myValue;
}
}

关于java - 如何将 java.util.Optional 与 REST API 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38777128/

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