java – 使用Gson添加现有的json字符串
发布时间:2020-05-24 18:12:37 所属栏目:Java 来源:互联网
导读:我有一个String对象包含一些任意的json.我想将它包装在另一个json对象中,像这样: { version: 1, content: arbitrary_json_string_object} 我如何可靠地添加我的json字符串作为属性,而不必手动构建(即避免繁琐的字符串连接)? class Wrapper { int version =
|
我有一个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编写一个自定义序列化程序. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
