在springboot中使用ModelAndView返回json 会多出多余的字段信息
代码如下:
public class TestDto implements Serializable {
private static final long serialVersionUID = 1727826299653600584L;
private int code;
private String name;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@GetMapping("/test")
public ModelAndView test(TestDto reqDto){
TestDto respDto=new TestDto();
respDto.setCode(1);
respDto.setName("response name");
//jackson config
Jackson2ObjectMapperBuilder builder=new Jackson2ObjectMapperBuilder();
ObjectMapper objectMapper=builder.build();
SimpleModule simpleModule=new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE,ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER,true);
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
MappingJackson2JsonView jonView= new MappingJackson2JsonView(objectMapper);
//return json
ModelAndView modelAndView = new ModelAndView(jonView);
modelAndView.addObject("message", respDto.getName());
modelAndView.addObject("code",respDto.getCode());
return modelAndView;
}
运行起来后 访问这个接口
http://192.168.1.210:9046/monitor/job/test?name=request name
返回了信息
我如何得到正确的json信息
{ "code": 1, "message": "response name json field" }
现在还有用ModelAndView的吗,你直接返回对象,加ResponseBody注解好啦
嗯,谢谢已经解决了