Richard Richard - 4 months ago 17
JSON Question

Is it possible to use variable as @JsonRootName?

I have a spring project and class like that and want to produce json with root name as type. Here is an example:

public class Person {
private String type; //worker
private String name; //Dennis
private String surname; //Ritchie
}


Result should be:

{"worker" : {
"name" : "Dennis" ,
"surname" : "Ritchie"
}
}


Can I do it with Json tags like @JsonRootName or should I write a Class for worker and extend Person class (There are 3 different types)?

Answer

You can implement a custom Serializer when you need to serialize a object into a JSON with a different form:

public class PersonSerializer extends JsonSerializer<Person> {
    @Override
    public void serialize(Person person, JsonGenerator jgen, SerializerProvider provider) 
        throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeFieldName(person.getType());
        jgen.writeStartObject();
        jgen.writeFieldName("name", person.getName());
        jgen.writeFieldName("surname", person.getSurname());
        jgen.writeEndObject();
        jgen.writeEndObject();
    }
}

After that, you can register the serializer on the class:

@JsonSerialize(using = PersonSerializer.class)
public class Person {
    private String type; 
    private String name; 
    private String surname; 
}