2017-07-24 48 views
3

我注意到,当我用Response.status(201).entity(id).build,它返回以下错误时:错误试图返回一个整数作为实体

严重:MessageBodyWriter找不到媒体类型=应用程序/ JSON,类型=级Java。 lang.Integer,genericType = class java.lang.Integer。

@POST 
    @Produces({"application/json"}) 
    public Response createUser(
      @NotNull @FormParam("username") String username, 
      @NotNull @FormParam("password") String password, 
      @NotNull @FormParam("role") String role) { 

     int id = 12; 
     return Response.status(201).entity(id).build(); 

    } 

回答

1

Integer对象不能被转换为JSON,因为JSON它就像图(键 - 值对)。你必须选择:

1)更改返回类型为文本

@Produces({"text/plain"}) 

2)创建一个类,它代表了一个价值为JSON,如:

class IntValue { 
    private Integer value; 

    public IntValue(int value) { 
     this.value = value; 
    } 

    // getter, setter 
} 

,然后执行以下

return Response.status(201).entity(new IntValue(id)).build(); 
0

"1"无效JSON。您应该将您的号码换成某个实体或将"application/json"更改为"application/text"

相关问题