我有一个包含任意 json 的字符串对象。我想将它包装在另一个 json 对象中,如下所示:
{
version: 1,
content: >>arbitrary_json_string_object<<
}
我如何才能可靠地将我的 json 字符串作为属性添加到它而无需手动构建它(即避免繁琐的字符串连接)?
class Wrapper {
int version = 1;
}
gson.toJson(new Wrapper())
// Then what?
请注意,添加的 json 应该不被转义,而是作为有效的 json 实体作为包装器的一部分,如下所示:
{
version: 1,
content: ["the content", {name:"from the String"}, "object"]
}
给予
String arbitraryJson = "[\"the content\", {name:\"from the String\"}, \"object\"]";
最佳答案
对于那些在这个话题上冒险的人,请考虑 this .
A a = getYourAInstanceHere();
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(a);
jsonElement.getAsJsonObject().addProperty("url_to_user", url);
return gson.toJson(jsonElement);
关于java - 使用 Gson 添加现有的 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20522550/