我有一个String对象包含一些任意的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\"]";
解决方法
这是我的解决方案:
Gson gson = new Gson(); Object object = gson.fromJson(arbitraryJson,Object.class); Wrapper w = new Wrapper(); w.content = object; System.out.println(gson.toJson(w));
在那里我改变了你的Wrapper类:
// setter and getters omitted
public class Wrapper {
public int version = 1;
public Object content;
}
如果要隐藏反序列化/序列化的详细信息,还可以为Wrapper编写一个自定义序列化程序.