大家讲道理2017-04-18 10:40:43
It is also possible to easily solve this problem by using fastjson, jackjson and other tools.
The following is my approach. If you think it is not good, please comment.
Create a Batch class with fields batchNo, List<Detail> detail;
public class Batch{
private String batchNo;
private List<Detail> detail;
//下面省略Get和Set方法……
}
public class Detail{
private String contractCode;
private int repayAmt;
private String repayType;
//下面省略Get和Set方法……
}
import org.codehaus.jackson.*; //这里我随便写的,反正就是用JackJson
public class BeanToJson{
public static void main(String[] args){
Batch batch = new Batch();
batch.setBatchNo("XX_20170120113655");
Detail detailA = new Detail();
Detail detailB = new Detail();
detailA.setContractCode("2017012001");
detailA.setRepayAmt(6600);
detailA.setRepayType("REPAY");
detailB.setContractCode("2017012002");
detailB.setRepayAmt(7600);
detailB.setRepayType("REPAY");
List<Detail> details = new ArrayList<Detail>();
details.add(detailA);
details.add(detailB);
batch.setDetail(details);
//上面都是一些设置数据的东西,下面才是要说的
ObejctMapper mapper = new ObjectMapper();
String s = mapper.writeValueAsString(batch);
// 现在 s 就是楼主想要的格式了。代码纯手打,不保证没有问题,想表达的是方法!
}
}
If you often want to change Bean into Json, this method is simple and clear.
伊谢尔伦2017-04-18 10:40:43
ArrayList<Map<String,String>> detail = new ArrayList<Map<String,String>>();
Pack a Map in a list