将Json映射到响应和异常的通用模型

时间:2015-02-21 12:21:01

标签: spring-mvc

抱歉我的英语不好提前:/

我想从RestController到任何对象构建响应,使用json中的通用模型,如下所示:

元:{"状态":则httpStatus} 数据:{"响应" :response}

和例外情况:

meta:{" status" :httpstatus," errorCode":" code"," message":" message"}, 数据:{}

有" HttpMessageConverter"和Objectmapper,但我不知道如何在我的情况下使用它 objectmapper使用"序列化器"来自杰克逊,但对于一个对象?

Spring 4.1.3

编辑:

像这样:

@RestController
@RequestMapping("..")
public class XXX {


@RequestMapping("..,consume/produce Json")
public ResponseEntity<T> method(@RequestBody arg)

T objectToReturn = ... ;


return new ResponseEntity<T>(objectToReturn, HttpStatus.CREATED);
}

...
}

1 个答案:

答案 0 :(得分:0)

对于你直截了当的情况,你可以使用Jackson 2,在序列化java类时忽略空字段。

您的控制器可能如下

public ResponseEntity<ResponseStatus> method(@RequestBody @Valid arg,BindingResult result){
        ResponseEntity<ResponseStatus> response = null;
        if(result.hasErrors()){
            Meta meta = new Meta(HttpStatus.BAD_REQUEST);
            ResponseStatus body = new ResponseStatus(meta,null);
            response = ResponseEntity.badRequest().body(body);
        }else{
              Meta meta = new Meta(HttpStatus.CREATED);
              Data data = service.data(arg);
              response = ResponseEntity.created(new URI("location"))
                         .body(new ResponseStatus(meta,data));
        }
        return response;
    }

其他课程将

//Ignore Null Fields on the Class
@JsonInclude(Include.NON_NULL)
class ResponseStatus{
 @Getter @Setter Meta meta;
 @Getter @Setter Data data;

 public ResponseStatus(Meta meta, data){
    this.meta = meta;
    this.data = data;
  }
}

//Ignore Null Fields on the Class
@JsonInclude(Include.NON_NULL)
class Meta{

 @Getter @Setter int status;
 @Getter @Setter String errorCode;
 @Getter Setter message;

 public Meta(HttpStatus httpStatus){
   status = httpStatus.value();
   message = httpStatus.getReasonPhrase();
   errorCode ="You code specific here";

 }
}