我指的是此示例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 }
但是现在我需要在课堂上添加一个arraylist并且需要序列化它,所以我添加了一个新的类帐户:
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'}]}
答案 0 :(得分:1)
我建议在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;
}