構造 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());
}
總結:
方式二的 putArray() 及 putObject() 可以在呼叫物件上返回一個空的 JSONArray 和 空的JSONObject,讓我們不再去new物件及關注何時做對映,比方式一靈活