gpt4 book ai didi

java - Jackon反序列化: how to reference another property?

转载 作者:行者123 更新时间:2023-12-01 12:05:40 25 4
gpt4 key购买 nike

鉴于此示例文档:

{
"currency": "USD",
"items": [{
"description": "foo",
"price": 100
}, {
"description": "bar",
"price": 50
}]
}

还有这些 Java 类

class Order {

Currency currency;

List<Item> items;

static class Item {

String description;

Money price;

}

static class Money {

BigDecimal amount;

@SomeDeserializationAnnotation("to reference currency from parent document Order")
Currency currency

}

}

是否存在类似@SomeDeserializationAnnotation(“从父文档订单引用货币”)

如果没有,是否可以使用自定义解串器?

最佳答案

首先,@JsonManagedReference 和 @JsonBackReference 在这里不起作用,因为:带注释的属性可以是bean、数组、Collection(List、Set)或Map类型,并且必须是bean属性(由使用BeanSerializer序列化类型的属性处理

其中货币字段是简单的字符串,默认情况下使用“FromStringDeserializer”(而不是 BeanDeserializer)。

您可以使用 Order 类的自定义反序列化器来解决您的问题,该反序列化器将转换值并使用可注入(inject)值来转换子对象:

@JsonDeserialize(using = OrderDeserializer.class)
class Order {
Currency currency;
List<Item> items;
}

class Item {
String description;
Money price;
}

class Money {
BigDecimal amount;
Currency currency;

public Money(BigDecimal amount, @JacksonInject Currency currency) {
this.amount = amount;
this.currency = currency;
}

}

class OrderDeserializer extends JsonDeserializer<Order> {

@Override
public Order deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectMapper objectCodec = (ObjectMapper)ctxt.getParser().getCodec();

JavaType listType = ctxt.getTypeFactory().constructCollectionType(List.class, Item.class);

JsonNode jsonNode = jp.readValueAsTree();
JsonNode currencyNode = jsonNode.get("currency");
JsonNode itemsNode = jsonNode.get("items");

Currency currency = objectCodec.treeToValue(currencyNode, Currency.class);

InjectableValues values = new InjectableValues.Std().addValue(Currency.class, currency);
List<Item> items = objectCodec.reader(listType).with(values).readValue(itemsNode);

return new Order(currency, items);
}
}

这里最大的缺点是,如果添加/删除/更新 Order 类,您将需要更新反序列化器实现。

关于java - Jackon反序列化: how to reference another property?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27639844/

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