0

I create a serializer which extend StdSerializer to transform a list of objects into many objects in json.

From

List<MyParentObject> myList = new LinkedList();    
public class MyParentObject{ private String nameOfObject; }

to

{
 "_elementNames":['object1','object2'],
 "object1":{...},
 "object2":{...}
}

It's working thanks to my serializer.

public class CustomElementListSerializer extends StdSerializer<List<AbstractElement>> {

    @Override
    public void serialize(List<AbstractElement> elements, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        List<String> eltNames = new LinkedList<>();
        System.err.println( serializerProvider.getActiveView());
        jsonGenerator.writeNull();
        for (AbstractElement element : elements) {
            String nameProperty = Element.getElement().getElementId();
            eltNames.add(nameProperty);
            jsonGenerator.writeFieldName(nameProperty);
            jsonGenerator.writeObject(element);                
        }          
        jsonGenerator.writeFieldName("_elementNames");
        jsonGenerator.writeStartArray();
        for (String eltName : eltNames) {
            jsonGenerator.writeString(eltName);
        }
        jsonGenerator.writeEndArray();        
    }
}

But I can't use in same time the @JsonView. Jackson doesn't take in account the annotation inside elements and serializerProvider.getActiveView() lost the information after one recursive call.

How I can solve my problem. Maybe the StdSerializer isn't the good solution. Or I miss how to took in account the JsonView inside a StdSerializer with the method

jsonGenerator.writeObject(element);
DAIRAV
  • 723
  • 1
  • 9
  • 31
Goofyrocks
  • 153
  • 1
  • 9

1 Answers1

0

I found a solution. You have to set a new mapper with the configuration of the current serializerProvider

ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
mapper.setConfig(serializerProvider.getConfig());
jsonGenerator.setCodec(mapper);
Goofyrocks
  • 153
  • 1
  • 9