springmvc配置gson的解析

文章目录

springmvc 排除jackson如果使用后使用Gson

1
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class,JacksonAutoConfiguration.class})

output

在autoconfig下gson的配置

image-20230409113435819如果直接使用expose注解后不会直接生效需要重新bean注入到

需要gson注入bean到spring里面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
new GsonBuilder()
.addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
final Expose expose = fieldAttributes.getAnnotation(Expose.class);
return expose != null && !expose.serialize();
}

@Override
public boolean shouldSkipClass(Class<?> aClass) {
return false;
}
})
.addDeserializationExclusionStrategy(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
final Expose expose = fieldAttributes.getAnnotation(Expose.class);
return expose != null && !expose.deserialize();
}

@Override
public boolean shouldSkipClass(Class<?> aClass) {
return false;
}
})
.create();

https://stackoverflow.com/questions/4802887/gson-how-to-exclude-specific-fields-from-serialization-without-annotations#:~:text=I%20explicitly%20used-,%40Expose%20to%20exclude,-it.%20I%20used