鉴于以下预期的JSON格式,我尝试使用Java生成JSON:
{
"stat": "ok",
"page": 1,
"total": 100,
"rows": [
{
"id":"1",
"cell":[
"content of column 1",
"content of column 2",
"content of column 3",
"content of column 4",
"content of column 5",
"content of column 6",
"content of column 7",
"content of column 8",
"content of column 9"
]
},
{
"id":"2",
"cell":[
"content of column 1",
"content of column 2",
"content of column 3",
"content of column 4",
"content of column 5",
"content of column 6",
"content of column 7",
"content of column 8",
"content of column 9"
]
},
到目前为止,我编写了以下代码,这些代码在某些方面很接近,但它不包含支持嵌套对象的逻辑。我发现这很困难,因为表示JSON对象所需的代码使用的HashMap类型的对象需要唯一的键。所以我需要有多个" id"条目,我只能用id输入一个hashmap键。我也尝试使用google / Guava multimap,但是在尝试同时投射或混合JSON库和google实现时存在限制。
以下代码将其生成为输出:
{
"total": "100",
"page": "1",
"stat": "ok",
"rows": [
{
"id": "1",
"cell": [
"test which represents one column's content",
"test, which contains 2nd column's data"
]
}
]
}
从上面可以看到的会很接近但不正确,因为它只包含1行和单元格。
public class GenerateJSON {
public static void main(String[] args) {
JSONArray cell = new JSONArray();
cell.add("test which represents one column's content");
cell.add("test, which contains 2nd column's data");
JSONObject ids = new JSONObject();
ids.put("id", "1");
ids.put("cell",cell);
HashMap<String,String> map = new HashMap(ids);
JSONArray rows = new JSONArray();
rows.add(ids);
JSONObject obj = new JSONObject();
obj.put("stat","ok");
obj.put("total","100");
obj.put("page","1");
obj.put("rows",rows);
System.out.println(obj);
}
}
答案 0 :(得分:0)
尝试以下代码可能会有效。
public static void main(String[] args) throws JSONException {
JSONObject obj = null;
JSONArray cellArray = new JSONArray();
JSONArray cellArray1 = new JSONArray();
for (int i = 0; i < 2; i++) {
obj = new JSONObject();
obj.put("id", i);
obj.put("cell", "contecnt 1, content 2, content 3");
cellArray.put(obj);
}
JSONObject responseData = new org.json.JSONObject();
responseData.put("rows", cellArray);
// System.out.println(responseData);
JSONObject obj1 = new JSONObject();
obj1.put("stat", "ok");
obj1.put("total", "100");
obj1.put("page", 1);
obj1.put("rows", responseData);
cellArray1.put(obj1);
JSONObject response = new org.json.JSONObject();
response.put("data", cellArray1);
System.out.println(response);
}
输出:
{"data":[{"total":"100","page":1,"stat":"ok",
"rows":
{"rows":[
{"id":0,
"cell":"contecnt 1, content 2, content 3"},
{"id":1,
"cell":"contecnt 1, content 2, content 3"}
]}
}]}
答案 1 :(得分:0)
如果这不是问题,你可以将它作为一个两步过程。
1)使用“文档”构建器在java中生成所需的json等效json。
2)将xml转换为json等效物很容易... 希望这有帮助!