您好,我是 Java 新手,非常感谢您的建议。我正在使用 gson-2.3.1,当我调用 toJson 或 fromJson 时,我意外地返回 null。我试图在一个更复杂的对象上进行此操作,因此我根据此处的用户指南回到了基础知识https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples 。下面的代码几乎完全复制,确实可以编译,但对我来说在往返情况下都返回 null 不起作用。只有字符串文字的情况才有效。非常感谢您的建议,谢谢!
//an object
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
// (Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson expgson2 = new Gson();
String json = expgson2.toJson(obj);
// here json in null - expected was the string below
String expectedjson = "{\"value1\":1,\"value2\":\"abc\"}";
// (Deserialization)
BagOfPrimitives obj2 = expgson2.fromJson(expectedjson, BagOfPrimitives.class);
// result is obj2 is null and not the object expected
最佳答案
我发现了问题。上面的所有代码都在一个方法中,所以我在编译器允许的类中声明了 BagofPrimitives 类,所以我认为这是可以的。请记住,我是 Java 新手,仍在学习中。一旦我将 BagofPrimitives 移到它所属的位置,代码就可以正常工作。
关于java - Gson fromJson 和 toJson 用于 Java 中返回 null 的简单对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27643435/