java 追加json,如何使用Java在现有的Json文件上追加数据?

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'

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值