2016-03-04 26 views
2

我需要在PlayFramework中使用來自Json的對象。從Json deseralization獲取必需的值到Java中的對象

Example example = Json.fromJson(request().body().asJson() , Example.class); 

但我需要始終具有對象中的所有值。

class Example{ 
    @Required_from_Json public String name; 
    @Required_from_Json public boolen dead; 
    @Required_from_Json public Integer age; 
    . 
    . 
50 more values 
} 

如果Json中的其中一個失蹤,它仍然會創建對象,但具有空值。我需要導致一些異常(可能是NullPointException),如果一些值在json中缺失或者對象是「null」而且它愚蠢地單獨檢查每個屬性(如年齡!= null)

你們有沒有任何意見?

謝謝!

回答

0

由於您的JSON對象來自請求,您可以使用Play的Form工具來處理您的情況。

在你的控制方法,你能簡單地叫它如下:

final Form<Example> form = Form.form(Example.class).bindFromRequest(); 

將數據從請求綁定。然後,你可以檢查,看看是否有任何這樣的錯誤:

if(from.hasErrors()) { 
     return badRequest(form.errorsAsJson()); 
    } 

和檢索的形式對象,如果沒有錯誤

Example obj = form.get(); 

你的榜樣類也需要改變使用Play的驗證約束上:

import play.data.validation.Constraints; 
... 

class Example{ 
    @Constraints.Required public String name; 
    @Constraints.Required public boolean dead; 
    @Constraints.Required public Integer age; 
    . 
    . 
    50 more values 
} 

編輯:我應該在這裏指出你的JSON對象的屬性名稱和p級roperty變量名稱必須是相同的映射才能自動工作。

這種方式是相當不錯的錯誤,它回報特定領域,所以你可以將它們展示給用戶,它會返回所有的錯誤在一個JSON對象(form.errorsAsJson())的所有字段。您還可以使用遊戲提供的其他驗證註釋(例如@Contraints.Email@Constraints.MinLenth等)

注意,這爲我工作在播放2.3.x的好處。我沒有使用最新版本的YMMV。

+0

你真了不起。謝謝精靈! :d – TyZet

0

此問題與您的問題非常相似。這不是遊戲,但仍有約傑克遜:

Configure Jackson to throw an exception when a field is missing

編輯:你可以通過自己創造的短驗證:

for (Field f : obj.getClass().getFields()) { 
    f.setAccessible(true); 
    if (f.get(obj) == null) { 
    // Throw error or return "bad request" or whatever 
    } 
} 

這個例子是基於Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

+0

嗨,你可以把50個值放到構造函數中嗎? – TyZet

+0

可怕的事情:),這個(和你的)問題的答案是「不」 - 所以你需要自己寫一些通用的驗證器 –

+0

看看我的答案中的新「編輯」部分請 –