Java spring引导:在嵌套对象中包含嵌套对象属性
在我的一个REST(-ish)控制器方法中,我收到一个json主体,如下所示:Java spring引导:在嵌套对象中包含嵌套对象属性,java,spring,spring-boot,jackson,Java,Spring,Spring Boot,Jackson,在我的一个REST(-ish)控制器方法中,我收到一个json主体,如下所示: { id: 123, otherId: 456, // ... other properties } 我想自动将其映射到具有以下结构的类 class Foo { int id; Bar otherId; // ... } 酒吧在哪里 class Bar { int id; } 因此,我想做的是将otherId映射到otherId.id(Bar.id)中的id,然后简单地将我的方法签名
{
id: 123,
otherId: 456,
// ... other properties
}
我想自动将其映射到具有以下结构的类
class Foo {
int id;
Bar otherId;
// ...
}
酒吧在哪里
class Bar {
int id;
}
因此,我想做的是将otherId
映射到otherId.id
(Bar.id)
中的id,然后简单地将我的方法签名更改为
@RequestMapping(...)
public void doThat(@RequestBody @Valid Foo)
是否有任何注释可以为我做到这一点,或者我必须自己编写包装方法,等等?这可能是我所希望的吗
关于您可以使用注释
@jsondeseligate
创建您自己的反序列化程序,如下所示:
class-Foo{
int-id;
@JsonDeserialize(使用=CustomDateDeserializer.class)
Bar otherId;
// ...
}
公共类CustomDateDeserializer扩展StdDeserializer{
@凌驾
公共项反序列化(JsonParser jp,反序列化上下文ctxt)
抛出IOException、JsonProcessingException{
JsonNode节点=jp.getCodec().readTree(jp);
int id=(Integer)((IntNode)node.get(“id”).numberValue();
字符串itemName=node.get(“itemName”).asText();
返回新项目(id、itemName、新条(id));
}
}
希望对您有所帮助您能将您的代码更改为使用@JsonDeserialize并为即将到来的帮助寻求者扩展STDESerializer吗?因为这是关于JSON->ObjectOk的,对不起,没问题。