构造 json 对象
需求:构造以下请求体
{
"attrSelectionVO": [
{
"attrAccessId": "eea99a0894504a2b89f3cfeb4be051d3",
"attrValueList": [
{
"attrValue": "输送型",
"attrValueAccessId": "52d54de77b224cc8b5f9af647c938b10",
}
],
"attributeName": "皮带形状",
"constraintCondition": 1,
"mergedRangeParamValue": null,
"paramName": null,
"paramValue": null,
"selectionSort": 2,
"type": 0
}
],
"categoryCode": "C02"
}
实现方式一:
@Test
public void test01(){
JSONObject requBody = new JSONObject();
JSONArray attrSelectionVOArray = new JSONArray();
requBody.put("attrSelectionVO", attrSelectionVOArray);
requBody.put("categoryCode","C02");
JSONObject attrSelectionVOEle = new JSONObject();
attrSelectionVOEle.put("attrAccessId", "eea99a0894504a2b89f3cfeb4be051d3");
JSONArray attrValueListArray = new JSONArray();
JSONObject attrValueListEle = new JSONObject();
attrValueListEle.put("attrValue", "输送型");
attrValueListEle.put("attrValueAccessId", "52d54de77b224cc8b5f9af647c938b10");
attrValueListArray.add(attrValueListEle);
attrSelectionVOEle.put("attrValueList", attrValueListArray);
attrSelectionVOEle.put("attributeName", "皮带形状");
attrSelectionVOEle.put("constraintCondition", 1);
attrSelectionVOEle.put("mergedRangeParamValue", null);
attrSelectionVOEle.put("paramName", "null");
attrSelectionVOEle.put("paramValue", "null");
attrSelectionVOEle.put("type", 0);
attrSelectionVOArray.add(attrSelectionVOEle);
System.out.println(requBody.toJSONString());
}
实现方式二:
@Test
public void test02(){
JSONObject requBody = new JSONObject();
JSONArray attrSelectionVOArray = requBody.putArray("attrSelectionVO");
requBody.put("categoryCode","C02");
JSONObject attrSelectionVOEle = attrSelectionVOArray.addObject();
attrSelectionVOEle.put("attrAccessId", "eea99a0894504a2b89f3cfeb4be051d3");
JSONArray attrValueListArray = attrSelectionVOEle.putArray("attrValueList");
JSONObject attrValueListEle = attrValueListArray.addObject();
attrValueListEle.put("attrValue", "输送型");
attrValueListEle.put("attrValueAccessId", "52d54de77b224cc8b5f9af647c938b10");
attrSelectionVOEle.put("attributeName", "皮带形状");
attrSelectionVOEle.put("constraintCondition", 1);
attrSelectionVOEle.put("mergedRangeParamValue", null);
attrSelectionVOEle.put("paramName", "null");
attrSelectionVOEle.put("paramValue", "null");
attrSelectionVOEle.put("type", 0);
System.out.println(requBody.toJSONString());
}
总结:
标签:fastjson,Java,JSONObject,attrSelectionVOEle,api,put,attrValueListEle,null,requBo From: https://www.cnblogs.com/czzz/p/18115516方式二的 putArray() 及 putObject() 可以在调用对象上返回一个空的 JSONArray 和 空的JSONObject,让我们不再去new对象及关注何时做映射,比方式一灵活