在gson序列化过程中省略HashMap名称

时间:2018-10-03 16:03:43

标签: java hashmap gson

我希望使用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 个答案:

答案 0 :(得分: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 ...;
    }
}