java-为什么gson不序列化此教程代码?

以下代码为我返回“ null”.

package test;

import com.google.gson.Gson;

class test {

    public static void main(String[] args) {

        class BagOfPrimitives {
              private int value1 = 1;
              private String value2 = "abc";
              private transient int value3 = 3;
              BagOfPrimitives() {
                // no-args constructor
              }
            }

        BagOfPrimitives obj = new BagOfPrimitives();
        System.out.println(obj.value1 + obj.value2 + obj.value3);
        Gson gson = new Gson();
        System.out.println(gson.toJson(obj));


    }

}

解决方法:

Gson使用幕后的reflection来确定对象的结构.在此特定示例中,BagOfPrimitives类是通过反射无法访问的局部类,因此Gson无法确定其结构.

而是使其成为独立的或嵌套的类.以下带有嵌套类的示例对我有用:

public class Test {

    public static void main(String[] args) {
        BagOfPrimitives obj = new BagOfPrimitives();
        System.out.println(obj.value1 + obj.value2 + obj.value3);
        Gson gson = new Gson();
        System.out.println(gson.toJson(obj));
    }

    static class BagOfPrimitives {
        private int value1 = 1;
        private String value2 = "abc";
        private transient int value3 = 3;
        BagOfPrimitives() {
            // no-args constructor
        }
    }

}
上一篇:SQLSTATE[22003]: Numeric value out of range: 1264 Out of range value for column 'contact'


下一篇:使用GSON将JSON对象转换为具有不同格式的Java对象