使用jax-rs

时间:2016-06-16 04:25:08

标签: java json jax-rs

我有一个要求。假设我有一个JSON文件,如下所示。

    {
    "orgId": 27,
    "orgType":"MotorBikes",
    "orgName":"ROYAL Enfield",
    "orgAddress":"Express Estate",
    "orgCity":"Chennai",
    "orgState":"TamilNadu"
    }

所以我需要做两次验证。一个是检查所有json字段并返回true或false,第二个应该有方法来验证部分响应,例如:isExists(jsonObject, "orgType":"MotorBikes")应该返回true。应使用jax-rs库进行此比较。所以,如果有任何熟悉此事的人请告诉我。这对我有很大帮助。

1 个答案:

答案 0 :(得分:0)

javax.json 就足够了。

import javax.json.JsonObject;

public static void main(String[] args){
    JsonObject jsonObj = /* your json */;
    boolean all = checkAll(jsonObj,new String[]{"orgId","orgType","orgName","orgAddress","orgCity","orgState"});        
    boolean one = isExists(jsonObj,"orgType","MotorBikes");
}

private boolean checkAll(JsonObject jsonObj, String[] keys) {
    for(String key: keys) {
        if(jsonObj.get(key)==null) return false;
    }
    return true;
}

private boolean isExists(JsonObject jsonObj, String key, String value) {
    return (jsonObj.get(key)!=null && jsonObj.get(key).equals(value));
}

<强>更新 使用 org.json 库的一个更集中的答案,它位于您的依赖项中,是一个JSON库,而不是JAX-RS。

@Test
public void test() throws FileNotFoundException{        
    String jsonAsString = when().get("/your.get").then().contentType(ContentType.JSON).extract().response().asString();
    JSONObject jsonFromResponse = new JSONObject(jsonAsString);

    File file = /** Load your file ***/             
    FileInputStream is = new FileInputStream(file);
    JSONTokener tokener = new JSONTokener(is);  
    while(tokener.more()) { // Iterate through Json file 
        JSONObject obj = (JSONObject) tokener.nextValue();
        for(String key: obj.keySet()) {     
            boolean valid = validateField(key, jsonFromResponse);
            System.out.println("'"+key+"' field "+(valid?"not ":"")+"present");
        }           
    }

    boolean v = validateValue(jsonFromResponse, "orgName", "ROYAL Enfield");    
    System.out.println("Validation: "+v);   
}

private boolean validateValue(JSONObject json, String key, String value) {
    if(validateField(key,json))
        return value.equals(json.getString(key));
    return false;
}

private boolean validateField(String key, JSONObject jsonFromResponse) {
    Object valueFromResponse = null;
    try {
        valueFromResponse = jsonFromResponse.get(key);
    }
    catch(JSONException e){
        valueFromResponse = null;
    }
    return valueFromResponse!=null;
}