Various JSON settings in Spring application for serializing REST and Ajax

In the Spring application, I added a custom JSON serializer that applies to the field with the thte tag:

@JsonSerialize(using=MySerializer.class)

And the MySerializer serializer (whcihc extends from JsonSerializer) has a method that looks like this:

@Override
public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException
{ 
    //some logic
}

It works and executes logic when an application generates json in methods annotated with @ResponseBody, but also executes the same logic when an application uses a web service with JSON. I would like to configure various configurations for serializing RestTemplate and for @ResponseBody, or at least be able to distinguish between the serialization method, regardless of whether we are in the case of @ResponseBody or in RestTemplate.

Any idea on how to do this?

Thank.

+1
1

Mix-in Annotations. , POJO :

class Root {

    private Data data;

    // getters/setters
}

class Data {

    private String name;

    // getters/setters
}

MixIn:

interface RootMixIn {

    @JsonSerialize(using = DataSerializer.class)
    Data getData();
}

, :

class DataSerializer extends JsonSerializer<Data> {

    @Override
    public void serialize(Data data, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException {
        generator.writeStartObject();
        generator.writeFieldName("name_property");
        generator.writeString(data.getName() + " XXX");
        generator.writeEndObject();
    }
}

, ObjectMapper. :

Data data = new Data();
data.setName("Tom");

Root root = new Root();
root.setData(data);

ObjectMapper mapperWithMixIn = new ObjectMapper();
mapperWithMixIn.addMixInAnnotations(Root.class, RootMixIn.class);

ObjectMapper mapperDefault = new ObjectMapper();

System.out.println("With MIX-IN");
System.out.println(mapperWithMixIn.writeValueAsString(root));

System.out.println("Default");
System.out.println(mapperDefault.writeValueAsString(root));

script :

With MIX-IN
{"data":{"name_property":"Tom XXX"}}
Default
{"data":{"name":"Tom"}}

, ObjectMapper MixIn ObjectMapper RestTemplate.

1

Spring ObjectMapper bean . bean. ? . :

bean mapperWithMixIn .

-, ObjectMapper bean bean RestTemplate-s bean /.

+2

Source: https://habr.com/ru/post/1534772/


All Articles