我有一个包含一些任意json的String对象.我想将它包装在另一个json对象中,如下所示:
{
version: 1,
content: >>arbitrary_json_string_object<<
}
Run Code Online (Sandbox Code Playgroud)
如何可靠地将我的json字符串作为属性添加到它而不必手动构建它(即避免繁琐的字符串连接)?
class Wrapper {
int version = 1;
}
gson.toJson(new Wrapper())
// Then what?
Run Code Online (Sandbox Code Playgroud)
请注意,新增JSON应该没有逃脱,但被包装为一个有效的JSON实体,像这样的一部分:
{
version: 1,
content: ["the content", {name:"from the String"}, "object"]
}
Run Code Online (Sandbox Code Playgroud)
特定
String arbitraryJson = "[\"the content\", {name:\"from the String\"}, \"object\"]";
Run Code Online (Sandbox Code Playgroud)
对于那些在这个主题上冒险的人,请考虑这一点.
A a = getYourAInstanceHere();
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(a);
jsonElement.getAsJsonObject().addProperty("url_to_user", url);
return gson.toJson(jsonElement);
Run Code Online (Sandbox Code Playgroud)
简单,将您的bean转换为a JsonObject并添加属性.
Gson gson = new Gson();
JsonObject object = (JsonObject) gson.toJsonTree(new Wrapper());
object.addProperty("content", "arbitrary_json_string");
System.out.println(object);
Run Code Online (Sandbox Code Playgroud)
版画
{"version":1,"content":"arbitrary_json_string"}
Run Code Online (Sandbox Code Playgroud)
这是我的解决方案:
Gson gson = new Gson();
Object object = gson.fromJson(arbitraryJson, Object.class);
Wrapper w = new Wrapper();
w.content = object;
System.out.println(gson.toJson(w));
Run Code Online (Sandbox Code Playgroud)
在哪里我改变了你的Wrapper课程:
// setter and getters omitted
public class Wrapper {
public int version = 1;
public Object content;
}
Run Code Online (Sandbox Code Playgroud)
Wrapper如果要隐藏反序列化/序列化的详细信息,也可以为自己编写自定义序列化程序.
| 归档时间: |
|
| 查看次数: |
14679 次 |
| 最近记录: |