1

I have a class

public class Car {
    public String color = null;
    public String brand = null;
    public HashMap<String,String> attributes;

    public Car() {
        this.attributes  = new HashMap<>();
    }

    public static void main( String[] args ) {
        Car car = new Car();
        car.color = "Red";
        car.brand = "Hyundai";
        car.attributes.put("key1", "value1");
        car.attributes.put("key2", "value1");

        Gson gson = new Gson();
        String json = gson.toJson(car);
        System.out.println(json);
    }
}

This currently serializes my car object into

{"color":"Red","brand":"Hyundai","attributes":{"key1":"value1","key2":"value1"}}

But I would like to unpack and serialize the attributes Dictionary from Car class as individual properties rather dictionary. Ideally, i would like my json to be,

{"color":"Red","brand":"Hyundai","key1":"value1","key2":"value1"}

How do I achieve the same in GSON?

UkFLSUI
  • 5,509
  • 6
  • 32
  • 47
Learner
  • 1,685
  • 6
  • 30
  • 42
  • You could write a custom serializer to serialize the object to your needs: https://stackoverflow.com/questions/6856937/gson-custom-serializer-in-specific-case/36979409 – Michiel May 03 '20 at 08:58
  • And then you need to maintain this serialiser and modify it every time you add a new attribute to your HashMap... – Joakim Danielson May 03 '20 at 09:01

2 Answers2

0

As explained in this Thread, there is no easy or straight forward way to achieve this. If there is a scope of using Jackson, it can be achieved using @JsonUnwrapped but it doesn't work with Maps as explained here

but there is work around.

 @JsonIgnore
 public HashMap<String,String> attributes;

 @JsonAnyGetter
 public HashMap<String, String> getAttributes() {
    return attributes;
 }

And this will help create the required JSON.

(new ObjectMapper()).writeValueAsString(car)

Note. This is an alternate approach.

lucid
  • 2,722
  • 1
  • 12
  • 24
0

Use @JsonAnyGetteron the getter of your attributes

Ankit Sharma
  • 1,626
  • 1
  • 14
  • 21