【问题标题】:Omitting HashMap name during gson serialization在 gson 序列化期间省略 HashMap 名称
【发布时间】:2018-10-03 16:03:43
【问题描述】:

我希望使用 gson 序列化我的课程,但我想省略 hashmap 名称。这对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
  }
}

【问题讨论】:

    标签: java hashmap gson


    【解决方案1】:

    写你自己的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 ...;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      相关资源
      最近更新 更多