GSON反序列化含嵌套对象数组的JSON失败问题求助
解决GSON解析时集合字段为null的问题
Hey,问题出在你的TheThing内部类上——它是私有非静态内部类,GSON没办法实例化这种依赖外部类实例的私有类,所以解析的时候theThings集合就始终为null了。给你几个可行的解决办法:
办法1:将TheThing改为静态内部类
静态内部类不依赖外部类的实例,GSON可以正常访问它的构造器和字段。修改后的代码如下:
package things; import java.io.Serializable; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class ThingsPOJO implements Serializable { @SerializedName("title") @Expose public String title = ""; @SerializedName("description") @Expose public String description = ""; @SerializedName("theThings") @Expose public List<TheThing> theThings = null; // 改为静态内部类 private static class TheThing implements Serializable { @SerializedName("thing") @Expose public String thing = ""; @SerializedName("association-type") @Expose public String associationType = ""; } }
办法2:将TheThing提取为独立公共类
如果TheThing的逻辑比较复杂,或者需要在其他地方复用,把它抽成独立的公共类会更清晰,GSON也能轻松处理:
创建TheThing.java文件:
package things; import java.io.Serializable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class TheThing implements Serializable { @SerializedName("thing") @Expose public String thing = ""; @SerializedName("association-type") @Expose public String associationType = ""; }
然后在ThingsPOJO中直接引用这个公共类即可:
package things; import java.io.Serializable; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class ThingsPOJO implements Serializable { @SerializedName("title") @Expose public String title = ""; @SerializedName("description") @Expose public String description = ""; @SerializedName("theThings") @Expose public List<TheThing> theThings = null; }
额外提示:确认GSON实例配置
虽然这不是你当前问题的核心,但如果你的GSON实例需要启用@Expose注解支持,记得用GsonBuilder配置:
Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .create(); ThingsPOJO pojo = gson.fromJson(yourJsonString, ThingsPOJO.class);
内容的提问来源于stack exchange,提问作者John Lippson
相关产品推荐
相关产品推荐

