Given the following expected JSON format, I am trying to generate JSON using Java:
{
"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"
]
},
I have thus far written the following code which is close in some regard, but it does not contain logic to supported nested objects. I find this difficult, because the code required to represent a JSON object uses a object that is of a HashMap type which requires unique keys. So where I need to have multiple "id" entries, I can only have one hashmap key entered with id. I also tried with google / Guava multimap, but there is a limitation in trying to cast or mix the JSON library and google implementation at the same time.
The below code generates this as the output:
{
"total": "100",
"page": "1",
"stat": "ok",
"rows": [
{
"id": "1",
"cell": [
"test which represents one column's content",
"test, which contains 2nd column's data"
]
}
]
}
which you can see from above, would be close but incorrect because it will only contain 1 x row and cell.
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);
}
}
Trying below code this might work.
Output: