简体   繁体   中英

Serialization from POJO of JSON Array

I have generated the below payload using serialization

{
  "transactionIds" : 123456,
  "test" : 3000,
  "amount" : {
    "currency" : "USD",
    "value" : 10
  }
}

Below is the code

    Amount a1 = new Amount();
    a1.setCurrency("USD");
    a1.setValue(10);

    Child a2 = new Child();
    a2.setTransactionIds(123456);
    a2.setTest(3000);
    a2.setAmount(a1);

    ObjectMapper mapper = new ObjectMapper();

    String abc = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(a2);

How do I add generate a payload such as the below, how should my getters / setters be

{
  "transactions": [
    {
      "transactionIds": 123456,
      "test": 3000,
      "amount": {
        "currency": "USD",
        "value": 10
      }
    }
  ]
}

I tried the below

private List<Child> transactions;

public List<Child> getTransactions() {
    return transactions;
}

public void setTransactions(List<Child> transactions) {
    this.transactions = transactions;
}

But I don't seem to get it working

    Parent a3 = new Parent();
    a3.setTransactions(a2);

Add a new class:

public class TransactionWrapper{
  private List<Child > transactions = new ArrayList<>();

  //getter setter

}

 Amount a1 = new Amount();
    a1.setCurrency("USD");
    a1.setValue(10);

    Child a2 = new Child();
    a2.setTransactionIds(123456);
    a2.setTest(3000);
    a2.setAmount(a1);

    TransactionWrapper tw = new TransactionWrapper();
    tw.getTransactions().add(a2);

    ObjectMapper mapper = new ObjectMapper();

    String abc = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(tw);

You can't write a3.setTransactions(a2); since setTransactions accepts a list of Child s not a single Child .

You must write something like this

if (a3.getTransactions() == null) {
    a3.setTransactions(new ArrayList<Child>());
}
a3.getTransactions().add(a2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM