toJson and fromJson returns null on very simple object

4,998 views
Skip to first unread message

Janet

unread,
Dec 25, 2014, 6:19:37 PM12/25/14
to googl...@googlegroups.com

Greetings I am new here and to Java and would much appreciate your advice.   I am using gson-2.3.1 and when I call either toJson or fromJson I unexpectedly get back null. I was attempting this on a much more complex object, so I went back to basics with the user guide here https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples . The code below is almost exactly copied, does compile but doesn't work for me returning the null in both to and from cases. Only the case with the string literal works. I know it's probably a total newbie mistake, but advice is much needed.   Thanks and Merry Christmas!

    //now 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

Inderjeet Singh

unread,
Dec 30, 2014, 1:00:20 PM12/30/14
to googl...@googlegroups.com
You shouldn't have got null on the toJson() call. This is not a newbie mistake, something seems messed up in your environment.
Can you run it through the debugger and see what is going on? 

Alex

unread,
Mar 12, 2015, 1:18:08 PM3/12/15
to googl...@googlegroups.com
I'm experiencing the same effect, even worse, actually, every combination of types and access level of the class members result in null returning for toJson().
As for the "environment", it's pretty clean room one. I've made a fresh IDEA project for it with nothing but JUnit and Gson 2.3.1 as dependencies. It is on Java 7.
Thoughts? 
Reply all
Reply to author
Forward
0 new messages