jeudi 31 mars 2016

Java Jackson serializer grab variable name

I have a class structure like so:

public class Foo {
    private Foo2 title;
    private Foo2 message;
}

public class Foo2 {
    private String value;
    private String variable;
}

When I serialize these classes into json I want to output the following json:

{
    "type": "title",
    "value": "...",
    "variable": "..."
},
{
    "type": "message",
    "value": "...",
    "variable": "..."
}

I made a custom serializer class like so:

public class FooSerializer extends JsonSerializer<Foo> {
    @Override
    public void serialize(Foo value,
                          JsonGenerator gen,
                          SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("type", /* get variable name */);
        gen.writeStringField("value", value.getValue());
        gen.writeStringField("variable", value.getVariable());
        gen.writeEndObject();
    }
}

But I'm not sure how to get the variable name. Am I going about this the right way? If so, how do I get the variable name?





Aucun commentaire:

Enregistrer un commentaire