gpt4 book ai didi

java - 类有 Jackson json 注释吗?

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

我有带有方法的 Controller 类:

@RequestMapping(value = "/createchild", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void createChild(@RequestBody Child child) {
childService.createChild(child);
}

当我使用这个 json 时,它可以工作:

{
"childfullname":"Lok Maen",
"password": "jfsddsf1",
"phonenumber": "+79695426314"
}

但是如果我想发布这样的内容:

    {
"another parameter": "123",
"child": {
"childfullname":"Lok Maen",
"password": "jfsddsf1",
"phonenumber": "+79155426314"
}
}

它不起作用。

子类:

@Entity
@Table(name = "child", schema = "cheer")
public class Child {

@Id
@Column(name = "childid")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long childId;

@JsonProperty("childfullname")
@Column(name = "childfullname")
private String childFullName;

@JsonProperty("password")
@Column(name = "password")
private String password;
// another code
}

如何修改代码以在 json 正文中再发布一个参数?

最佳答案

你需要使用2个类来实现你想要的:

public class CreateChildRequestDTO {
@JsonProperty("another parameter")
private String anotherParameter;

@JsonProperty("child")
private ChildDTO child;
}

public class ChildDTO {
@JsonProperty("childfullname")
private String childFullName;

@JsonProperty("password")
private String password;

@JsonProperty("phonenumber")
private String phonenumber;
}

并将 Controller 方法更改为:

@RequestMapping(value = "/createchild", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void createChild(@RequestBody CreateChildRequestDTO createChildRequest ) {
...
}

请注意,在您的示例中,您使用实体类作为 DTO,这是一种不好的做法。对此进行了解释:Mixing entity with payload (dto) in spring boot - best practice .

关于java - 类有 Jackson json 注释吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60003399/

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