我正在尝试使用这种精确的JSON语法但无法实现它:
{
"sun":"yellow",
"vegetables":[{
"apple":"red",
"banana":"yellow",
"melon":"orange"
}]
}
我能得到的最接近的是:
{
"sun":"yellow",
"vegetables":["{
"apple":"red",
"banana":"yellow",
"melon":"orange"
"]}
}
这就是我在做的事情:
JSONObject json = new JSONObject();
json.put("sun","yellow");
ArrayList<HashMap<String,Object>> test = new ArrayList<HashMap<String,Object>>();
HashMap<String,Object> params = new HashMap<String, Object>();
params.put("apple","red");
params.put("banana","yellow");
params.put("melon","orange");
test.add(params);
json.put("fruits",test);
我无法理解,我错过了什么?
答案 0 :(得分:5)
应该是这样的 -
JSONObject json = new JSONObject();
json.put("sun","yellow");
JSONArray veg = new JSONArray();
JSONObject vegData = new JSONObject();
vegData.put("apple","red");
vegData.put("banana","yellow");
vegData.put("melon","orange");
veg.put(vegData);
json.put("vegetables",veg);
我正在使用Jettison
。您可以找到详细信息here。
答案 1 :(得分:0)
为什么不进行嵌套?一些例子here
JSONObject outer = new JSONObject();
JSONObject inner = new JSONObject();
JSONArray array = new JSONArray();
outer.put("sun", "yellow");
array.put("apple", "red");
array.put("bannanna", "yellow");
array.put("melon", "orange");
inner.put(array);
outer.put("Vegtables":inner);