GSON将所有字段反序列化json字符串

时间:2018-09-03 18:56:39

标签: java json gson

我有一个具有如此多字段的Java对象...

 public class Foo {
        private String field0;
        private String field1;
        private String field2;
        private String field3;
        private String field4;
        private String field5;
        private String field6;
        private String field7;
        private String field8;
        private String field9;

        // Getters and Setters...

    }

我有以下JSONString ...

{\"field0\": \"value0\", \"field1\": \"value1\"}

我用GsonBuilder()实例化Gson如下...

        gson = new GsonBuilder()//
                .disableHtmlEscaping()//
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) //
                .setPrettyPrinting()//
                .serializeNulls()//
                .setDateFormat("yyyy/MM/dd HH:mm:ss [Z]")//
                .create();

当我打电话给gson.fromJson(JSONString, Foo.class);时,我得到了一个Foo的新实例,所有字段都设置为null。甚至在我的JsonString中指定的field0field1 ...

如何反序列化上面的JSONString以获取设置了field0field1的实例?

1 个答案:

答案 0 :(得分:1)

您设置了FieldNamingPolicy.UPPER_CAMEL_CASE,将JSON字符串更改为{\"Field0\": \"value0\", \"Field1\": \"value1\"}