3

以下代码为我返回“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));


    }

}
4

1 回答 1

4

Gson 在幕后使用反射来确定对象结构。该类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
        }
    }

}
于 2012-10-22T02:40:59.120 回答