gpt4 book ai didi

java - Json 和 Array 序列化 - Java Spring Boot

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

我正在尝试插入手机列表,但没有成功。

我的域客户端类

@Entity   
public class Client {

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integir id;
private String name;
@JsonManagedReference
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(****)
private List<Phone> phones = new ArrayList<>();
**gets and sets**

public Client (String name){
this.name = name;
}
}

我的域电话类

@Entity
public class Phone {

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integir id;
private String number;
@JsonBackReference
@ManyToMany(mappedBy = "phones")
private List<Client> clients = ArrayList<>();
**gets and sets**
public Phone(String number) {
this.number = number;
}
}

我有一个 DTO 客户端DTO

public class ClientDTO {

private String name;
private String number;
private List<Phone> numbers = ArryList<>();
**gets and sets**
}

我的服务ClientService有这个方法:

public Client fromDTO (ClientDTO clientDTO) {

Client c = new Client(clientDTO.getName());
for(Phone p: clientDTO.getNumbers()) {
p.setNumber(x.getNumber);
p.getClients().addALL(Arrys.asList(c));
c.getPhones().addAll(Arrys.asList(p));
}
}

如果我在 postman 中尝试这样做:

{
"name" : "Teste",
"numbers":
[
{ "number" : "xxxxxx"},
{ "number" : "yyyyyyy"}
]
}

显示错误 415:不支持的媒体类型

如果我将 ClientDTO 更改为:

public class ClientDTO {

private String name;
private String number;
**gets and sets**
}

我在 ClientService 中的方法是:

public Client fromDTO (ClientDTO clientDTO) {

Client c = new Client(clientDTO.getName());
Phone p = new Phone(clientDTO.getPhone());

p.getClients().addAll(Arrys.asList(c));
c.getPhones().addAll(Arrays.asList(p));
}

在我的 postman 中我发送了这个:

{
"name" : "Teste",
"number": "xxxxx"
}

工作正常。

我做错了什么?

最佳答案

向客户端和电话实体类添加一个空(无参数)构造函数

客户端实体类

@Entity   
public class Client {

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integir id;
private String name;
@JsonManagedReference
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(****)
private List<Phone> phones = new ArrayList<>();
**gets and sets**

public Client (){}
public Client (String name){
this.name = name;
}
}

电话实体类

@Entity
public class Phone {

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integir id;
private String number;
@JsonBackReference
@ManyToMany(mappedBy = "phones")
private List<Client> clients = ArrayList<>();
**gets and sets**

public Phone() {}
public Phone(String number) {
this.number = number;
}
}

如果对象没有可序列化的父类(super class)并且没有无参数构造函数,则无法序列化该对象。由于您在 ClientDTO 中使用了 Phone 实体类,并且它没有无参数构造函数,因此序列化过程失败

关于java - Json 和 Array 序列化 - Java Spring Boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51001992/

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