如何拆分json数组

时间:2016-10-18 16:08:52

标签: java json

我得到了这段代码:

   public static void main(String[] args) {

        JSONObject profiles = new JSONObject();
        profiles.put("Name", "Roger");
        profiles.put("Age", "Twenty");

        try {
            File profiles_file = new File("D:\\profiles.txt");
            profiles_file.createNewFile();
            FileWriter fileWriter = new FileWriter(profiles_file);
            fileWriter.write(profiles.toJSONString());
            fileWriter.flush();
            System.out.print(profiles);

        } catch (IOException e) {
        }

    }
}

当我运行代码时,文件获取此数据:

  

{"年龄":"二十""名称":"罗杰"}

我遇到了问题,我想知道如何以这种格式插入数据:

  

[{年龄:"二十",姓名:" Roger" }]

如果我插入2次数据(代码中的适当更改(追加)),我想得到这个:

  

[{年龄:"二十",姓名:" Roger" },

     

{年龄:"二十",姓名:" Roger" }]

提前谢谢你, NearDaniel。

1 个答案:

答案 0 :(得分:0)

JSONArray profiles = new JSONArray();

JSONObject profile1 = new JSONObject();
profile1.put("Name", "Roger");
profile1.put("Age", "Twenty");

JSONObject profile2 = new JSONObject();
profile2.put("Name", "Roger");
profile2.put("Age", "Twenty");

profiles.add(profile1);
profiles.add(profile2);