Search code examples
javajacksonjackson2

How to marshall the nested content of a class but without adding the attribute name as its key


I have this class:

public class EnvironmentInformation implements Serializable {

    private final String[] profiles;

    //GETTERS/SETTERS

An object of this class is added to a map with a key "environment". When I marshall the map using Jackson's object mapper I get:

{"environment":{"profiles":["dev"]}}

However what I would like to get is:

{"environment": ["dev"]}

Is there any way to customize the marshalling process to get that result?

Notice I cannot modify the EnvironmentInformation class structure (I could add annotations though),


Solution

  • Solved implementing JsonSerializable:

    public class EnvironmentInformation implements Serializable, JsonSerializable {
    
        private final String[] profiles;
    
        public EnvironmentInformation(String[] environment) {
            this.profiles = environment;
        }
    
        public String[] getProfiles() {
            return profiles;
        }
    
        @Override
        public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeStartArray();
            for (String fooValue : getProfiles()) {
                gen.writeString(fooValue);
            }
            gen.writeEndArray();
        }
    
        @Override
        public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
            serialize(gen, serializers);
        }
    }