org.springframework.hateoas.EntityModel<> serialization by JACKSON

Viewed 24

I just started learning Jackson and I don't understand why serialization is OK when I create, for example, Person.class:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class Person {
    String name;
    Details details;
}

and nested Details.class looks like:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@JsonSerialize(using = DetailsSerializer.class)
public class Details {
    String surname;
    int age;
    String email;
}

My custom serializer DetailsSerializer.class looks like

@Override
public void serialize(Details details, JsonGenerator gen, SerializerProvider provider) throws IOException {
    gen.writeStartObject();
    gen.writeStringField("surname",details.getSurname());
    gen.writeNumberField("ageee", details.getAge());
    gen.writeEndObject();
}

But when I create Enum Unit and custom serializer 'UnitSerializer' for it:

@JsonDeserialize(using = UnitDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
@Getter
public enum Unit {
    //big enum
}
package com.schegolevalex.unit_library.entities.units;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;

public class UnitSerializer extends StdSerializer<Unit> {
    public UnitSerializer(){
        this(Unit.class);
    }

    public UnitSerializer(Class<Unit> t) {
        super(t);
    }

    @Override
    public void serialize(Unit unit, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("fullName",unit.getFullName());
        gen.writeStringField("unitType",unit.getUnitType().name());
        gen.writeStringField("subtype",unit.getSubtype());
        gen.writeStringField("shortName",unit.getShortName());
        gen.writeEndObject();
    }
}

and then return to client org.springframework.hateoas.EntityModel<Unit> object from my controller I get exception with the message

Resolved [org.springframework.http.converter.HttpMessageNotWritableException: 
Could not write JSON: Can not start an object, expecting field name (context: Object); 
nested exception is com.fasterxml.jackson.databind.JsonMappingException: 
Can not start an object, expecting field name (context: Object) 
(through reference chain: org.springframework.hateoas.EntityModel["content"])]

Field " content" from EntityModel<T> in my case is Unit content, custom serialization class for Unit is present. Do I need to create custom serializer to EntityModel now? Why Jackson can not serialize EntityModel automatically?

0 Answers
Related