2015-11-19 82 views
0

我正在下載一個json文件,並且內容可用作數組數組。驗證json文件

有各種驗證(notNull,isNumber等),我想要做的孩子數組的元素。

一個是當我使用Spring批處理,並啓用ValidatingItemProcessor和Bean驗證適用於我。

但是,我想用Apache等現有的Validator框架編寫獨立的解決方案,但不想驗證爲bean,而是直接在陣列上進行驗證。

我應該怎樣解決這個問題。

我使用的是Spring框架,所以任何圍繞它的東西都會有所幫助。

回答

1

我們對我們的spring批處理應用程序使用了JSR驗證。我們使用@ NotNull,@ DecimalMin等驗證方式對我們的類進行註釋。然後我們創建了一個CommonValidator,如

import javax.validation.Validator; 
... 
public class CommonValidator<T> implements ItemProcessor<T, T>{ 

    @Autowired 
    private Validator validator; 

    public T process(T t) throws Exception{ 
     Set<ConstraintViolation<T>> constraintViolations = validator.validate(t); 
     return constraintViolations.isEmpty()? t : null; 
    } 

然後,我們將它添加到CompositeItemProcessor中,如下所示。

<bean id="validateProcessor" class="mypackage.CommonValidator" /> 
class="org.springframework..CompositeItemProcessor"> 
     <property name="delegates"> 
      <list> 
       <ref bean="validateProcessor"/> 
       <ref bean="otherProcessor"/> 

它工作。在類似的行上,你可以編寫你自己的驗證器來驗證你的數組。所以,如果數組值是有效的,那麼返回數組。 null返回無效數組。