[英]Java spring boot: include nested object property in nesting object
在我的一种 REST(-ish) controller 方法中,我收到了一个 json 主体,如下所示:
{
id: 123,
otherId: 456,
// ... other properties
}
我想将 map 自动转换为具有以下结构的 class
class Foo {
int id;
Bar otherId;
// ...
}
酒吧在哪里
class Bar {
int id;
}
所以我想做的是 map otherId
到otherId.id
(Bar.id)
中的 id 并简单地将我的方法签名更改为。
@RequestMapping(...)
public void doThat(@RequestBody @Valid Foo)
是否有任何注释可以为我做到这一点,或者我必须自己编写包装方法等? 这可能是我希望的方式吗?
问候
您可以使用注释@JsonDeserialize
创建自己的反序列化器,如下所示:
class Foo {
int id;
@JsonDeserialize(using = CustomDateDeserializer.class)
Bar otherId;
// ...
}
public class CustomDateDeserializer extends StdDeserializer<Bar> {
@Override
public Item deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
int id = (Integer) ((IntNode) node.get("id")).numberValue();
String itemName = node.get("itemName").asText();
return new Item(id, itemName, new Bar(id));
}
}
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.