[英]How to add append a new class object to the existing JSON file in Java?
[英]How do i add an attribute in an existing json file using java
我需要在系統中已經具有的json文件中添加一個具有動態值的資源類型屬性。
我嘗試編寫代碼,但是沒有用
這是我擁有的json(我只共享前幾行)
{
"id": "example",
"text": {
"status": "generated",
而我編寫代碼后所需的輸出是
{
"resourceType": "Patient",
"id": "example",
"text": {
"status": "generated",
添加了resourceType字段,並且我們根據要求獲得了屬性的值
您可以使用ObjectMapper
在POJO中反序列化它,設置屬性並將其反序列化回String,例如:
class Example {
private String id;
private String resourceType;
private Text text;
//getters and setters
}
class Text {
private String status;
//getters and setters
}
public static void main(String[] args) throws Exception {
String string = "{\n" +
" \"id\": \"example\",\n" +
" \"text\": {\n" +
" \"status\": \"generated\""
+ "} "
+ "}";
ObjectMapper objectMapper = new ObjectMapper();
Example example = objectMapper.readValue(string, Example.class);
example.setResourceType("Patient");
System.out.println(objectMapper.writeValueAsString(example));
}
這是傑克遜的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.