2017-07-24 52 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"

相關問題