@DataTimeFormat、@ResponseStatus、jackson

@DateTimeFormat

以下为一接口的代码示例:

@ApiOperation(value = "获取设备历史数据", response = DevicePropertyModel.class, responseContainer = "PagedList")
@GetMapping(value = "/history/{deviceId}", produces = "application/json")
public PagedList<DevicePropertyModel> getHistoryProperty(
  @PathVariable("deviceId") int deviceId,
  @RequestParam(required = false, defaultValue = "") String queryStr,
  @RequestParam(required = false, defaultValue = "1") int page,
  @RequestParam(required = false, defaultValue = "20") int pageSize,
  @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime from,
  @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime to) {
        return devicePropertyService.getHistoryByDeviceId(deviceId, queryStr, page, pageSize, from, to);
    }

如果接口中出现**@RequestParam @DateTimeFormat(iso =DateTimeFormat.ISO.DATE_TIME)LocalDateTime to**,这样的请求参数,那么在url请求time的请求格式中应是"time":“2017-02-12T12:00:00”。

在GET请求中,不能使用@RequestBody。

在POST请求,可以使用@RequestBody和@RequestParam,但是如果使用@RequestBody,对于参数转化的配置必须统一。

举个例子,在SpringMVC配置了HttpMessageConverters处理栈中,指定json转化的格式,如Date转成‘yyyy-MM-dd’,则参数接收对象包含的字段如果是Date类型,就只能让客户端传递年月日的格式,不能传时分秒。

因为不同的接口,它的参数可能对时间参数有不同的格式要求,所以这样做会让客户端调用同事对参数的格式有点困惑,所以说扩展性不高。

如果使用@RequestParam来接受参数,可以在接受参数的model中设置@DateFormat指定所需要接受时间参数的格式。

@ResponseStatus

这个注解是用来标注在一个类或方法上,用来做异常类。**@ResponseStatus(value = HttpStatus.CREATED)**表示一个http请求的相应结果。

jackson注解

@JsonInclude,测试用例中传参

在做测试类的时候,如果实现请求参数丢失或者http信息不可读,或是传到controller类处的参数为null,注意:

可能是在url中传递的参数不符合controller类中接口定义的传递参数类型。或是在content中传递的@RequestBody中传递参数集格式不对,如要求传递一个数组,但是却传递了一个单个变量。

也可能是,在传递参数的某个实例中,用了@JsonProperty(这个注解是用来,重新定义传递参数在转成json格式数据后的名称。

如这个属性在对象中定义的是fullName, 标注这个注解@JsonProperty(value = “full_name”)后,在json数据中该字段显示的名称为full_name),@JsonInclude的注解,则用JSONObect.toJSONString()无法识别解析以上两个注解,则无法在转成正确的json数据格式。则可以用jakson中的方法来解析:

第一种:

String json=new ObjectMapper().writeValueAsString(zone);

MvcResult mvcResult=mvc.perform(MockMvcRequestBuilders.post(url)
.header("Authorization","Bearer "+token)
.contentType(MediaType.APPLICATION_JSON).content(json)
.accept(MediaType.APPLICATION_JSON))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andReturn();

第二种:

StringWriter sw = new StringWriter();
JsonGenerator generator=mapper.getFactory().createGenerator(sw);   
generator.writeObject(regionDetail);
String json = "["+sw.toString()+"]";

MvcResult mvcResult=mvc.perform(MockMvcRequestBuilders.put(url)
.header("Authorization","Bearer "+token)
.contentType(MediaType.APPLICATION_JSON).content(json))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andReturn();

@JsonInclude(Include.NON_NULL)

@JsonInclude(Include.NON_NULL) 这个注解放在类头上就可以解决。 实体类与json互转的时候 属性值为null的不参与序列化

实际效果

在这里插入图片描述

在这里插入图片描述

发布了51 篇原创文章 · 获赞 0 · 访问量 729

猜你喜欢

转载自blog.csdn.net/lxy1740/article/details/104308305