Java学习-030-JSON 之四 -- 判断 JSONObject 是否包含键值对

前文对获取 JSON 数据封装方法,使之可通过类似于 cssSelector 的方法获取 JSON 数据,使获取数据变得简单。敬请参阅:模仿 cssSelector 封装读取 JSON 数据方法

在日常的测试中,需要验证 JSON 数据中某一个值是否正确,再次封装一个方法,验证 JSONObject 中是否包含特定的键值。

直接上码了:

/**
 * Aaron.ffp Inc.
 * Copyright (c) 2004-2015 All Rights Reserved.
 */
package com.demo;

import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;

/**
 * 
 * @author Aaron.ffp
 * @version V1.0.0: Jsoup com.demo ITestHome.java, 2015-8-31 19:03:15 Exp $
 */
public class ITestHome {
    private String request = "http://mb.51buy.com/json.php?mod=home&act=config";
    private Logger logger = Logger.getLogger(this.getClass());
    private String message = "";
    private Document doc;
    private String test;
    
    /**
     * send request and get response
     * 
     * @author Aaron.ffp
     * @version V1.0.0: Jsoup com.demo ITestHome.java beforeTest, 2015-8-31 19:04:05 Exp $
     * 
     * @throws IOException
     */
    @BeforeTest
    public void beforeTest() throws IOException{
        this.doc = Jsoup.connect(this.request).data("appSource","android")
                .userAgent("Jsoup demo")
                .cookie("user", "Jsoup")
                .timeout(5000).get();
        this.test = doc.select("body").get(0).text();
    }
    
    /**
     * 
     * 
     * @author Aaron.ffp
     * @version V1.0.0: Jsoup com.demo ITestHome.java test_isJSONObjectContainKV, 2015-9-2 20:24:56 Exp $
     * 
     * @throws IOException
     */
    @Test
    public void test_isJSONObjectContainKV() throws IOException {
        System.out.println("

==================================== test_isJSONObjectContainKV");
        
        System.out.println("errno --> " + this.isJSONObjectContainKV(new JSONObject(this.test), "errno:0"));
        System.out.println("title:星星 --> " + this.isJSONObjectContainKV(new JSONObject(this.getJsonText(this.test, "$data|#floor|$1|#colmunInfo|$0")), "title:星星"));
    }
    
    /**
     * Assert the key-value exist or not in the JSONObject
     * 
     * @author Aaron.ffp
     * @version V1.0.0: Jsoup com.demo ITestHome.java isJSONObjectContainKV, 2015-9-2 20:05:18 Exp $
     * 
     * @param jsonObject : JSONObject
     * @param kv         : key:value
     * 
     * @return boolean
     */
    public boolean isJSONObjectContainKV(JSONObject jsonObject, String key_value){
        boolean flag = false;
        
        try{
            if (jsonObject == null) {
                new NullPointerException("The argument {" + jsonObject + "} is null, please check this!");
                
                return flag;
            }
            
            // assert key_value : null, empty, whitespace
            if (StringUtil.isBlank(key_value) || !"2".equals(String.valueOf(key_value.split(":").length)) || 
                StringUtil.isBlank(key_value.split(":")[0]) || StringUtil.isBlank(key_value.split(":")[1])) {
                this.message = "The argument {" + key_value + "} is invalid, please check this!";
                this.logger.warn(this.message);
                
                return flag;
            }
            
            String act = jsonObject.get(key_value.split(":")[0]).toString();
            String exp = key_value.split(":")[1];
            
            // assert the actual value is expected or not
            if (exp.equals(act)) {
                flag = true;
            }
        } catch (JSONException je){
            this.message = je.getMessage();
            this.logger.error(this.message);
            
            return flag;
        }

        return flag;
    }
    
    /**
     * Get JSON Object {JSONObject, JSONArray, text} by json selector
     * 
     * @author Aaron.ffp
     * @version V1.0.0: Jsoup com.demo ITestHome.java getJsonText, 2015-9-1 19:40:12 Exp $
     * 
     * @param json     : JSON string
     * @param selector : JSON selector
     *        $key|$key|#array|#int|$int|key
     *        #key|#int
     *        $key|#key|$int
     *        key
     *        
     *        array|key : is illegal
     *        key|$     : is illegal
     *        key|#     : is illegal
     *        key|key   : is illegal
     * @return
     */
    public String getJsonText(String json, String selector){
        JSONObject jo = null;
        JSONArray  ja = null;
        String jsonText = "";
        String item     = "";
        String flag     = "O"; // O - JSONObject; A - JSONArray; T - text 
        
        // arguments must not be null
        if (json == null || selector == null) {
            this.message = "The argument {" + json + "} and {" + selector + "} must be not null, please check this!";
            this.logger.error(this.message);
            
            new IllegalArgumentException(this.message);
        }
        
        // return empty if the json is empty
        if ("".equals(json)) {
            return "";
        }
        
        // return json if the selector is empty
        if ("".equals(selector)) {
            return json;
        }
        
        try{
            jo = new JSONObject(json);
            
            String[] select = selector.split("\|");
            
            for (int i = 0; i < select.length; i++) {
                item = select[i];
                
                // throw exception when selector against the rule
                if (flag.equals("T") || (flag.equals("A") && (!item.startsWith("O") || !item.startsWith("A") || !StringUtil.isNumeric(item.substring(1))))) {
                    new IllegalArgumentException("The argument {" + selector + "} is invalid to the define rule of selector, please check this!");
                }
                
                if (item.startsWith("#")) {          // get JSONArray
                    if (flag.equals("A")) {
                        ja = ja.getJSONArray(Integer.valueOf(item.substring(1)));
                    } else if (flag.equals("O")){
                        ja = jo.getJSONArray(item.substring(1));
                    }
                    
                    flag = "A";
                } else if (item.startsWith("$")){    // get JSONObject
                    if (flag.equals("O")) {
                        jo = jo.getJSONObject(item.substring(1));
                    } else if (flag.equals("A")){
                        jo = ja.getJSONObject(Integer.valueOf(item.substring(1)));
                    }
                    
                    flag = "O";
                } else {                             // get text
                    jsonText = jo.get(item).toString();
                    
                    flag = "T";
                }
            }
        } catch (JSONException jsone){
            jsone.printStackTrace();
        }
        
        switch (flag) {
            case "O":
                return jo.toString();
            case "A":
                return ja.toString();
            default:
                return jsonText;
        }
    }
}

运行结果如下图所示:

各位也可修改上述源码中的第 98 行,以满足不同方式的对比判断,例如:相等、包含、起始、结尾等。

 

至此, Java学习-030-JSON 之四 -- 判断 JSONObject 是否包含键值对 顺利完结,希望此文能够给初学 Java 的您一份参考。

最后,非常感谢亲的驻足,希望此文能对亲有所帮助。热烈欢迎亲一起探讨,共同进步。非常感谢! ^_^

 

原文地址:https://www.cnblogs.com/fengpingfan/p/4807177.html