Gson解析:declares multiple JSON fields named XXX

1:异常信息

Exception in thread "main" java.lang.IllegalArgumentException: class com.wizincloud.messageText.model.MessageText declares multiple JSON fields named created_at
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:122)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:72)
    at com.google.gson.Gson.getAdapter(Gson.java:356)
    at com.google.gson.Gson.toJson(Gson.java:585)
    at com.google.gson.Gson.toJson(Gson.java:572)
    at com.google.gson.Gson.toJson(Gson.java:527)
    at com.google.gson.Gson.toJson(Gson.java:507)
    at com.Test.main(Test.java:23)

2:Model类

Gson解析:declares multiple JSON fields named XXX_第1张图片

Gson解析:declares multiple JSON fields named XXX_第2张图片

测试类:

public class Test {
    public static void main(String[] args) {
        Gson g = new Gson();
        MessageText mt = new MessageText();
        mt.setCreated_at(new Date());
        System.out.println(g.toJson(mt));
    }

}

3:解决办法

(1)将model类MessageText中的字段created_at去掉。
(2)将model类MessageText中需要打印的字段created_at加上注解@Expose
Gson解析:declares multiple JSON fields named XXX_第3张图片

BaseModel中的created_at不加@Expose注解,被排除掉!

Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

excludeFieldsWithoutExposeAnnotation排除掉没有Expose注解的属性。

你可能感兴趣的:(json,gson,exception)