- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
鉴于此示例文档:
{
"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/
这是我使用@JsonDeserialize 的属性 @Transient @JsonDeserialize(using = SharedUserDeserializer.class) private
我使用 Jackson 对我的 Spring Boot 项目进行序列化/反序列化。 我有一个具有以下结构的 DTO 对象, public class TestDTO implements Serial
我正在尝试使用自定义日期格式反序列化 JSON。它失败了,即使我在对象映射器上设置了日期格式: SimpleDateFormat dateFormat = new SimpleDateForm
我有一个使用 Apache CXF 的 JAX-RS API。最近我从 Jettison 切换到 Jackson (2.7.1) 来处理 JSON。我正在使用 JacksonJaxbJsonProvi
我是一名优秀的程序员,十分优秀!