How to append data on a existing Json file using Java?

后端 未结 1 538
执笔经年
执笔经年 2020-12-22 14:56

This is my current Json data in a Json file call student.json

{\"name\":\"Mahesh\",\"age\":10}

I want to Append to the fol

相关标签:
1条回答
  • 2020-12-22 15:33

    Update

    Oh seems I forgot to post the original json file. Pls put the student.json with below content: (Need to wrap with [ & ] to make it an array)

    [{"name":"Mahesh","age":10}]
    

    Because you can not just append objects to original object, it will violate JSON syntax, the way to make it correct is to put them into an array.

    Original answer

    You should change to use an array to store multiple objects. And use FileWriter to output.

    Pls try this code, it works in my locl env:

    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    
    import org.json.simple.parser.JSONParser;
    import org.json.simple.parser.ParseException;
    
    import java.io.*;
    
    public class JsonWritingProject {
    
        public static void main(String[] args) {
            JSONParser jsonParser = new JSONParser();
    
            try {
                Object obj = jsonParser.parse(new FileReader("D:\\student.json"));
                JSONArray jsonArray = (JSONArray)obj;
    
                System.out.println(jsonArray);
    
                JSONObject student1 = new JSONObject();
                student1.put("name", "BROCK");
                student1.put("age", new Integer(3));
    
                JSONObject student2 = new JSONObject();
                student2.put("name", "Joe");
                student2.put("age", new Integer(4));
    
                jsonArray.add(student1);
                jsonArray.add(student2);
    
                System.out.println(jsonArray);
    
                FileWriter file = new FileWriter("D:\\student.json");
                file.write(jsonArray.toJSONString());
                file.flush();
                file.close();
    
            } catch (ParseException | IOException e) {
                e.printStackTrace();
            }
    
        }
    }
    

    And the library dependency is:

    dependencies {
        compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1'
    }
    
    0 讨论(0)
提交回复
热议问题