java:使用Spring-ResponseEntity响应json格式接口

使用Spring-ResponseEntity可以响应json格式的数据,非常方便。

控制器端代码:

@RequestMapping(value = "/channel/{id}", method = RequestMethod.GET)
public ResponseEntity getChannelById() throws InterruptedException {
    return new ResponseEntity<>("success.", HttpStatus.OK);
}

以上结果输出:"success.",如果参数是一个Object呢?我们需要返回一个json格式。首先,需要定义一个标准返回格式

@JsonInclude(Include.NON_EMPTY)
public class ResponseEnvelope {
	@Getter
	private Integer code;
	@Getter
	private String message;
	@Getter
	private T data;
    
	public ResponseEnvelope(Integer code, String message, T data) {
		this.code = code;
		this.message = message;
		this.data = data;
	}
}

在控制器这样调用:

@RequestMapping(value = "/channel/test", method = RequestMethod.GET)
public ResponseEntity> getChannelById() throws InterruptedException {
    return new ResponseEntity<>(new DapResponseEnvelope(200, "success.", "test"), HttpStatus.OK);
}

以上结果输出:{"code":200,"message":"success.","data":"test"}。如果data传入的也是Object,还会被格式化成json的数据。

 

可能遇到的问题:

HttpMessageNotWritableException: No converter found for return value of type

需要添加依赖


    com.fasterxml.jackson.core
    jackson-databind
    2.9.5


    com.fasterxml.jackson.core
    jackson-annotations
    2.9.5

 

你可能感兴趣的:(Java)