如何用Java构建json对象
在使用java构建json之前,首先需要先明确json的概念:https://blog.csdn.net/qq_35885488/article/details/80310062
啥是JSONObject
,啥是JSONArray
。
下面是两个例子:
json
{
"RequestHead":{
"BusiType":"LIS-WX000-02",
"SaleChnl":"WX",
"DataType":"03"
},
"RequestBody":{
"AppntAge":"53",
"AppntIDType":"0",
"AppntIDNo":"430623196811027890",
"BEContNo":"11111",
"AppntSex":"男",
"AppntBirthday":"1968-11-02",
"AppntName":"张三",
"RiskList":[
{
"RiskCode":"001",
"Mult":"1",
"MainRiskCode":"001",
"PayIntv":"5",
"Prem":"100000",
"Amnt":"100000",
"InsuYearFlag":"Y",
"PayYear":"5",
"InsuYear":"10"
}
]
}
}
javacode
JSONObject head = new JSONObject();
head.put("BusiType", "LIS-WX000-02");
head.put("SaleChnl", "WX");
head.put("DataType", "03");
JSONObject body = new JSONObject();
body.put("BEContNo" , "11111");
body.put("AppntName" , "张三");
body.put("AppntSex" , "男");
body.put("AppntBirthday" , "1968-11-02");
body.put("AppntIDType" , "0");
body.put("AppntIDNo" , "430623196811027890");
body.put("AppntAge" , "53");
JSONObject risk = new JSONObject();
risk.put("MainRiskCode", "001");
risk.put("RiskCode" , "001");
risk.put("Prem" , "100000");
risk.put("Amnt" , "100000");
risk.put("Mult", "1");
risk.put("PayIntv" , "5");
risk.put("PayYear" , "5");
risk.put("InsuYear" , "10");
risk.put("InsuYearFlag" , "Y");
JSONArray ar = new JSONArray();
ar.add(risk);
body.put("RiskList", ar);
JSONObject req = new JSONObject();
req.put("RequestHead", head);
req.put("RequestBody", body);
// System.out.println(req.toJSONString());
LOGGER.debug(req.toJSONString());
json
{
"insuredList":[
{
"insuredSex":0,
"insuredAge":62,
"riskInfoList":[
{
"planCodeInfoList":[
{
"insuYear":"5",
"payIntv":"0",
"dutyCode":"DPE131",
"payEndYear":"1000",
"prem":"200000"
}
],
"riskcode":"PE13"
}
]
}
]
}
code
public static void paramJson(){
JSONObject head = new JSONObject();
head.put("dutyCode","DPE131");
head.put("insuYear","5");
head.put("payEndYear","1000");
head.put("payIntv","0");
head.put("prem","200000");
JSONArray ar = new JSONArray();
ar.add(head);
JSONObject head1 = new JSONObject();
head1.put("riskcode","PE13");
head1.put("planCodeInfoList",ar);
JSONObject head2 = new JSONObject();
head2.put("insuredAge",62);
head2.put("insuredSex",0);
JSONArray ar3 = new JSONArray();
ar3.add(head1);
head2.put("riskInfoList",ar3);
JSONArray ar1 = new JSONArray();
ar1.add(head2);
JSONObject head3 = new JSONObject();
head3.put("insuredList",ar1);
System.out.println(head3);
}
这里使用的是alibaba
的fastjson
,记得引入依赖