为了账号安全,请及时绑定邮箱和手机立即绑定

在 gson 序列化期间省略 HashMap 名称

在 gson 序列化期间省略 HashMap 名称

长风秋雁 2021-10-27 10:48:20
我希望使用 gson 序列化我的类,但我想省略哈希图名称。gson可以做到吗?我曾尝试编写自己的 TypeAdapter,但地图名称仍写为父对象。我有一个看起来像的课程public class myClass {    @Expose    public Long timestamp;    @Expose    public String id;    @Expose    public HashMap<String, someOtherClass> myMap = new HashMap<>();    @Override    public String toString() {        Gson gson = new GsonBuilder()                .excludeFieldsWithoutExposeAnnotation()                .create();        return gson.toJson(this);    }}电流输出:{  "timestamp": 1517245340000,  "id": "01",  "myMap": {    "mapKey1": {      "otherClassId": "100", // works as expected    }    "mapKey2": {      "otherClassId": "101", // works as expected    }  }}我希望得到什么:{  "timestamp": 1517245340000,  "id": "01",  "mapKey1": {      "otherClassId": "100", // works as expected  },  "mapKey2": {      "otherClassId": "100", // works as expected  }}
查看完整描述

1 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

自己写TypeAdapter。例如,参见 javadoc。


用@JsonAdapter注解指定它,或者用 注册它GsonBuilder。


@JsonAdapter(MyClassAdapter.class)

public class MyClass {

    public Long timestamp;

    public String id;

    public HashMap<String, SomeOtherClass> myMap = new HashMap<>();

}

public class MyClassAdapter extends TypeAdapter<MyClass> {

    @Override public void write(JsonWriter out, MyClass myClass) throws IOException {

        // implement the write method

    }

    @Override public MyClass read(JsonReader in) throws IOException {

        // implement the read method

        return ...;

    }

}


查看完整回答
反对 回复 2021-10-27
  • 1 回答
  • 0 关注
  • 139 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信