Dimitrije M
Dimitrije M

Reputation: 383

Omitting HashMap name during gson serialization

I am looking to serialize my class using gson but I would like to omit the hashmap name. Is this possible with gson?

I have tried writing my own TypeAdapter but the map name is still written as the parent object.

I have a class which looks like

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);
    }
}

current output :

{
  "timestamp": 1517245340000,
  "id": "01",
  "myMap": {
    "mapKey1": {
      "otherClassId": "100", // works as expected
    }
    "mapKey2": {
      "otherClassId": "101", // works as expected
    }
  }
}

What I am hoping to get :

{
  "timestamp": 1517245340000,
  "id": "01",
  "mapKey1": {
      "otherClassId": "100", // works as expected
  },
  "mapKey2": {
      "otherClassId": "100", // works as expected
  }
}

Upvotes: 2

Views: 110

Answers (1)

Andreas
Andreas

Reputation: 159106

Write your own TypeAdapter. See javadoc for example.

Specify it with @JsonAdapter annotation, or register it with 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 ...;
    }
}

Upvotes: 1

Related Questions