gpt4 book ai didi

java - 如何向 JSON 字符串添加附加属性?

转载 作者:行者123 更新时间:2023-11-30 06:50:03 25 4
gpt4 key购买 nike

import com.google.gson.Gson;
Gson gson = new Gson()
String s = gson.toJson(obj, type);

我想在上面的 Json 字符串中添加一个类型不存在的附加属性。我该怎么做?

最佳答案

您可以使用 gson.toJsonTree(..) 方法来做同样的事情,下面是相同的工作示例:-
1. 使用toJsonTree(Object src)获取 src 对象作为 JsonElements 树的等效表示的方法。
2. 调用getAsJsonObject() ON 在步骤 1 中检索到的 JsonElement 以将其获取为 JsonObject。
3.在JsonObject中添加属性在第 2 步中,使用 addProperty(..) 方法。

class Employee{

public Employee(String name){
this.name= name;
}
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

public class GsonTest {
public static void main(String[] args) {
Gson gson = new Gson();
Employee employee=new Employee("Amit");
String s=gson.toJson(employee, Employee.class);
System.out.println(s);
JsonElement jsonElement = gson.toJsonTree(employee);
jsonElement.getAsJsonObject().addProperty("dept", "IT");
s=gson.toJson(jsonElement);
System.out.println(s);
}

/** Output
{"name":"Amit"}
{"name":"Amit","dept":"IT"}
*/

您的代码更改将是:-

JsonElement jsonElement = gson.toJsonTree(obj);
jsonElement.getAsJsonObject().addProperty("new_property", "new_property_value");
s=gson.toJson(jsonElement);

关于java - 如何向 JSON 字符串添加附加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41844604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com