Java 在gson序列化期间忽略HashMap名称

Java 在gson序列化期间忽略HashMap名称,java,hashmap,gson,Java,Hashmap,Gson,我希望使用gson序列化我的类,但我想省略hashmap名称。这对gson有可能吗 我已经尝试编写自己的TypeAdapter,但映射名仍然作为父对象编写 我有一门课看起来像 public class myClass { @Expose public Long timestamp; @Expose public String id; @Expose public HashMap<String, someOtherClass> myMap

我希望使用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",
  "mapKey1": {
      "otherClassId": "100", // works as expected
  },
  "mapKey2": {
      "otherClassId": "100", // works as expected
  }
}
写你自己的。例如,参见javadoc

使用注释指定它,或使用注册它

@JsonAdapter(MyClassAdapter.class)
公共类MyClass{
公共长时间戳;
公共字符串id;
public HashMap myMap=new HashMap();
}
公共类MyClassAdapter扩展了TypeAdapter{
@重写公共void write(JsonWriter out,MyClass MyClass)引发IOException{
//实现write方法
}
@重写公共MyClass读取(JsonReader in)引发IOException{
//实现read方法
返回。。。;
}
}
{
  "timestamp": 1517245340000,
  "id": "01",
  "mapKey1": {
      "otherClassId": "100", // works as expected
  },
  "mapKey2": {
      "otherClassId": "100", // works as expected
  }
}
@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 ...;
    }
}