This is my current Json data in a Json file call student.json
{"name":"Mahesh","age":10}
I want to Append to the following data, output should be like this
{"name":"Mahesh","age":10}, {"name":"BROCK","age":3}, {"name":"Joe","age":4}
This my current code
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonWritingProject
{
public static void main(String[] args)
{
JSONObject main = new JSONObject();
JsonParser jsonParser = new JsonParser();
try
{
Object obj = jsonParser.parse(new FileReader("student.json"));
JSONObject jsonObject = (JSONObject) obj;
jsonObject.put("BROCK", 3);
jsonObject.put("Joe", 4);
System.out.println(jsonObject.toString());
} catch (JsonIOException | JsonSyntaxException | FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It is not working, what should I do? Please advise
解决方案
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'
}