Professor Chaos
Professor Chaos

Reputation: 9060

Custom json serialization tweak

I have a class like this

class MData
{
   String version;
   String ttl;
   Foo[] foos;
}

where Foo is class Foo {String key; String value}

and serializing an instance of MData using gson creates json like this

{
    "version" : "1.0",
    "ttl" : 4,
    "foos" : [ {"key" : "fooKey1", "value" : "fooValue1" } , {"key" : "fooKey2", "value" : "fooValue2" }]
}

but I was wondering if there is a way to manipulate the json generation to something like this

{
    "version" : "1.0",
    "ttl" : 4,
    "fooKey1" : "fooValue1",
    "fooKey2" : "fooValue2" 
}

without having to rewrite the original class or introduce an intermediate type.

I have a lot of existing entities that have the key/value attribute and the requirement is to have a flat json and I'm looking into a way to tweak the generation so I can get the desired output.

Upvotes: 3

Views: 76

Answers (1)

Vivin Paliath
Vivin Paliath

Reputation: 95488

I think you're looking for Custom Serializers and Deserializers. I really wouldn't recommend the kind of custom serialization you're doing though. because it is changing the semantics of the data. Custom serializers are usually used if you want to filter or transform some data without changing its semantics.

That being said, you can do something like this:

public class MDataSerializer implements JsonSerializer<MData> {

    @Override
    public JsonElement serialize(MData src, Type typeOfSrc, JsonSerializationContext context) {

        JsonObject obj = new JsonObject();
        obj.addProperty("version", src.version);
        obj.addProperty("ttl", src.ttl);

        for(Foo foo : src.foos) {
            obj.addProperty(foo.getKey(), foo.getValue());
        }

        return obj;
    }
}

Upvotes: 3

Related Questions