如何使用java向现有json文件添加新数据(整数)[已关闭]

2guxujil  于 2022-12-05  发布在  Java
关注(0)|答案(1)|浏览(134)

Closed. This question needs details or clarity . It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post .

Closed 2 days ago.
Improve this question
This is my JSON file(student.json)
{ "studentName": "steve", "studentLocation": [ { "locationArea": "us", "address": { "addressLine1": "xyz", "addressLine2": "abc" }, "locationCode": "123" } ], "startDate": "2023-01-05", "endDate": "2023-02-05" }
need to add new data in existing json file using java code
{ "studentName": "steve", "studentLocation": [ { "locationArea": "us", "address": { "addressLine1": "xyz", "addressLine2": "abc" }, "locationCode": "123" } ], "startDate": "2023-01-05", "endDate": "2023-02-05", "pincode": { ------>new line "pin": 123456 ------>integer value }
}

dba5bblo

dba5bblo1#

正确格式化您的代码。将您提供的Json放在代码标记中。下面介绍如何。

如果你想用java编辑一个Json文件,你应该使用一个库,比如gson

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.10</version>
</dependency>

如果你使用gson,你可以这样做:

Gson gson = new Gson();
JsonElement element = gson.fromJson(new FileReader("path-to-your-file"))
element.getAsJsonObject().add("pin", new JsonPrimitive(123456))

切勿使用完整路径因为如果您移动项目或将项目交给其他人,完整路径可能不可靠。考虑查看this,以确保无论您的项目位于何处,始终可以找到您的文件。

相关问题