springboot 中使用FastJsonView注解无效
在springboot中通过bean设置将解析改为fastjson。fastjson版本为1.2.36 Controller端代码如下,程序正常运行,但是字段还是返回了Test中的全部字段内容。 @RequestMapping("ob") @FastJsonView( include = {@FastJsonFilter(clazz = Test.class,props={"descn"})}, exclude = {@FastJsonFilter(clazz = Test.class,props = {"id","name"})} ) public @ResponseBody Test ob(){ Test test = new Test(); test.setId(22); test.setName("badaf"); test.setDescn("hjhh"); test.setAaa("aaa"); return test;
}
@smallsun848 配置 FastJsonHttpMessageConverter、FastJsonViewResponseBodyAdvice 了吗?
@lihengming FastJsonHttpMessageConverter配置如下,FastJsonViewResponseBodyAdvice 需要怎么配置?
@SpringBootApplication @MapperScan("com.example.test1.dao") public class Test1Application {
public static void main(String[] args) {
SpringApplication.run(Test1Application.class, args);
}
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,SerializerFeature.WriteMapNullValue);
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
}
问题解决了。因为FastJsonViewResponseBodyAdvice 配置了component,而springboot默认不会去扫描,指定了扫描的路径就可以了。
@SpringBootApplication @MapperScan("com.example.test1.dao") @ComponentScan({"com.alibaba.fastjson.support.spring","com.example.test1.controller"}) public class Test1Application {
I think so: @ControllerAdvice MyFastJsonViewResponseBodyAdvice extends FastJsonViewResponseBodyAdvice{ }
springboot版本: 2.0.1.RELEASE fastjson版本: 1.2.46
FastJsonViewResponseBodyAdvice
@RestControllerAdvice
public class MyFastJsonViewResponseBodyAdvice extends FastJsonViewResponseBodyAdvice {
}
TsetController
@RestController
@RequestMapping("/test")
public class TestController {
private static final Logger logger = Logger.getLogger(TestController.class);
@GetMapping(path = "address")
@FastJsonView(include = @FastJsonFilter(clazz = Address.class, props = {"city"}))
public Address testFastJsonView() {
Address address = new Address();
address.setCity("city");
address.setStreet("street");
address.setDistrict("district");
address.setNumber("number");
address.setComment("comment");
return address;
}
}
Test
@RunWith(SpringRunner.class)
@WebMvcTest(TestController.class)
public class AddressTest {
@Autowired
private MockMvc mvc;
@Test
public void testExample() throws Exception {
MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/test/address")
.accept(MediaType.APPLICATION_JSON)).andReturn();
System.out.println(result.getResponse().getContentAsString());
}
}
Address的字段都输出了
{"city":"city","district":"district","street":"street","number":"number","comment":"comment"}
控制台中输出了 Detected ResponseBodyAdvice implementation in myFastJsonViewResponseBodyAdvice 但是我在FastJsonViewResponseBodyAdvice中的方法打断点,发现并没有执行到断点处。 请问这是什么问题?是因为我配置有问题还是程序的问题?有什么解决方案吗?