使用数组在java中创建一个JSON文件

时间:2018-02-26 19:41:05

标签: java json multidimensional-array

我使用JSON-simple-1.1.1,我想创建一个像这样的JSON文件:

    {
       "data": [
           [
               "1",
               "YES",
               "sp_1",
               "1",
               "xxx"
           ],
           [
               "2",
               "NO",
               "sp_2",
               "2",
               "yyyy"
           ],
           [
               "3",
               "YES",
               "sp_3",
               "2",
               "zzzz"
           ]
       ]
   }

我尝试使用JSONObjectJSONArray,但我无法解决如何创建如上所述的多数组

1 个答案:

答案 0 :(得分:0)

小帮手让生活更轻松:

public static JSONArray jsonArray(Object... values) {
    JSONArray arr = new JSONArray();
    arr.addAll(Arrays.asList(values));
    return arr;
}

然后:

JSONObject obj = new JSONObject();
obj.put("data", jsonArray(jsonArray("1", "YES", "sp_1", "1", "xxx"),
                          jsonArray("2", "NO" , "sp_2", "2", "yyyy"),
                          jsonArray("3", "YES", "sp_3", "2", "zzzz")));
System.out.println(obj.toJSONString());

输出

{"data":[["1","YES","sp_1","1","xxx"],["2","NO","sp_2","2","yyyy"],["3","YES","sp_3","2","zzzz"]]}