gpt4 book ai didi

java - Jackson:反序列化 ArrayList 不起作用?

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

我指的是这个例子here序列化我的对象。

我最初有这个并且它有效。

public class MyClass implements Serializable {
private String mediaitem_id;
private String customer_id;
private int quantity;

public MyClass(String item, String customer, int quantity){
this.mediaitem_id = item;
this.customer_id = customer;
this.quantity = quantity;
}

public String toJson(){
ObjectMapper mapper = new ObjectMapper();

try{
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE);
return mapper.writeValueAsString(this);
}catch(Exception ex){
log.error("Error converting MyClass to json " + this, ex);
}

return "";
}
}

MyClass myClass = new MyClass("1234", "23234", 5);

myClass.toJson() 给出以下内容,这就是我想要的:

{ mediaitem_id: '1234', customer_id: '23234', quantity: 5 }

但是现在我需要向类中添加一个数组列表,并且还需要对其进行序列化,因此我添加了一个新类 Account:

public static class Account implements Serializable {
public String accountname;
public String accountid;

public Account(String accountname, String accountid) {
this.accountname = accountname;
this.accountid = accountid;
}
}

public class MyClass implements Serializable {
private String mediaitem_id;
private String customer_id;
private int quantity;
private List<Account> accounts = new ArrayList<>();

public MyClass(String item, String customer, int quantity){
this.mediaitem_id = item;
this.customer_id = customer;
this.quantity = quantity;
}

public void addAccount(String accountname, String accountid) {
Account anAccount = new Account(accountname, accountid);
accounts.add(anAccount);
}

public String toJson(){
ObjectMapper mapper = new ObjectMapper();

try{
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE);
return mapper.writeValueAsString(this);
}catch(Exception ex){
log.error("Error converting MyClass to json " + this, ex);
}

return "";
}
}

MyClass myClass = new MyClass("1234", "23234", 5);
myClass.addAccount("acc-01", "a001");
myClass.addAccount("acc-02", "a002");

myClass.toJson() 仍然给出相同的结果:

{ mediaitem_id: '1234', customer_id: '23234', quantity: 5 }

我现在缺少什么?

我想要得到类似的东西:

{ mediaitem_id: '1234', customer_id: '23234', quantity: 5, accounts: [{accountname: 'acc-01', accountid: 'a001'}, {accountname: 'acc-02', accountid: 'a002'}]}

最佳答案

我建议为 MyClass 中的所有属性添加 getter 和 setter。

public String getMediaitem_id() {
return mediaitem_id;
}

public void setMediaitem_id(String mediaitem_id) {
this.mediaitem_id = mediaitem_id;
}

public String getCustomer_id() {
return customer_id;
}

public void setCustomer_id(String customer_id) {
this.customer_id = customer_id;
}

public int getQuantity() {
return quantity;
}

public void setQuantity(int quantity) {
this.quantity = quantity;
}

public List<Account> getAccounts() {
return accounts;
}

public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}

关于java - Jackson:反序列化 ArrayList 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46641523/

25 4 0