• Java学习-031-JSON 之五 -- 特定数据获取(JSONObject满足特定键值)


    前面几篇博文分别讲述了 JSON 的 概要知识简单数据获取封装cssSelector数据获取方法JSONObject 是否包含 key_value,请自行阅读相关博文。

    在日常的接口测试脚本编写过程中,经常需要依据有个特定的条件,获取条件匹配数据对应的其他属性的值。例如,在验证订单信息的接口测试脚本中,我们首先需要获取订单列表,然后通过订单编号找到对应的订单,再获取订单对应的支付金额、配送信息等数据;当然,也可直接获取订单信息,然后获取相应的数据。此文主要讲述第一种情况,当请求响应中含有多个相似的数据信息列表时,若何获取满足特定 key_value 的 JSONObject 并获取相应的 key 对应的 value。

    直接上源码:

    /**
     * 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_getJSONObjectItemTextUseKV, 2015-9-3 21:31:45 Exp $
         *
         */
        @Test
        public void test_getJSONObjectItemTextUseKV(){
            JSONObject jo = new JSONObject(this.getJsonText(this.test, "$data|#floor|$1|#colmunInfo|$0"));
            String key_value = "title:星星";
            String key = "picUrl";
            
            if (this.isJSONObjectContainKV(jo, key_value)) {
                this.message = key_value + " --> " + this.getJSONObjectItemTextUseKV(jo, key_value, key) + "
    ";
                
                System.out.println(this.message);
            } else {
                this.message = "{" + key_value + "} not macth the JSONObject " + jo.toString() + "
    ";
                
                System.out.println(this.message);
            }
            
            key_value = "title:范丰平 - 博客园";
            if (this.isJSONObjectContainKV(jo, key_value)) {
                this.message = key_value + " --> " + this.getJSONObjectItemTextUseKV(jo, key_value, key) + "
    ";
                
                System.out.println(this.message);
            } else {
                this.message = "{" + key_value + "} not macth the JSONObject " + jo.toString() + "
    ";
                
                System.out.println(this.message);
            }
            
            key_value = "范丰平:博客园";
            if (this.isJSONObjectContainKV(jo, key_value)) {
                this.message = key_value + " --> " + this.getJSONObjectItemTextUseKV(jo, key_value, key) + "
    ";
                
                System.out.println(this.message);
            } else {
                this.message = "{" + key_value + "} not macth the JSONObject " + jo.toString() + "
    ";
                
                System.out.println(this.message);
            }
            
            key_value = "title:相机九月发券";
            if (this.isJSONObjectContainKV(jo, key_value)) {
                this.message = key_value + " --> " + this.getJSONObjectItemTextUseKV(jo, key_value, key) + "
    ";
                
                System.out.println(this.message);
            } else {
                this.message = "{" + key_value + "} not macth the JSONObject " + jo.toString() + "
    ";
                
                System.out.println(this.message);
            }
        }
        
        /**
         * Get the text from JSONObject which the key_value was included.
         * 
         * @author Aaron.ffp
         * @version V1.0.0: Jsoup com.demo ITestHome.java getJSONObjectItemTextUseKV, 2015-9-3 20:24:31 Exp $
         * 
         * @param jsonObject : JSONObject
         * @param key_value  : key and value    
         * @param key        : key
         * 
         * @return String
         */
        public String getJSONObjectItemTextUseKV(JSONObject jsonObject, String key_value, String key){
            if (jsonObject == null) {
                return "";
            }
            
            if (StringUtil.isBlank(key_value) || StringUtil.isBlank(key)) {
                this.message = "The argument {" + key_value + "} must be not null and empty, please check this!";
                logger.error(this.message);
                
                new IllegalArgumentException(this.message);
            }
            
            if (!"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!";
                logger.error(this.message);
                
                new IllegalArgumentException(this.message);
            }
            
            if (this.isJSONObjectContainKV(jsonObject, key_value)) {
                return jsonObject.get(key).toString();
            } else {
                this.message = "Can't find the " + key_value + "in the JSONObject {" + jsonObject.toString() + "}. Please check this!";
                this.logger.warn(this.message);
                
                System.out.println(this.message);
                return "";
            }
        }
        
        /**
         * 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;
            String actValue = "";
            
            String key = key_value.split(":")[0];
            String expValue = key_value.split(":")[1];
            
            
            try{
                if (jsonObject == null) {
                    throw new NullPointerException("The first argument {" + jsonObject + "} is null, please check this!");
                }
                
                // assert key_value : null, empty, whitespace
                if (StringUtil.isBlank(key_value) || !"2".equals(String.valueOf(key_value.split(":").length)) || 
                    StringUtil.isBlank(key) || StringUtil.isBlank(expValue)) {
                    this.message = "The second argument {" + key_value + "} is invalid, please check this!";
                    this.logger.warn(this.message);
                    
                    throw new IllegalArgumentException(this.message);
                }
                
                if (this.isJSONObjectContainKey(jsonObject, key)) {
                    actValue = jsonObject.get(key).toString();
                    
                    // assert the actual value is expected or not
                    if (expValue.equals(actValue)) {
                        flag = true;
                    }
                } else {
                    this.message = "The key {" + key + "} not exist, please check this.";
                    this.logger.warn(this.message);
                }
            } catch (JSONException je){
                this.message = je.getMessage();
                this.logger.error(this.message);
                
                return flag;
            }
    
            return flag;
        }
        
        /**
         * Assert key is included in JSONObject or not.
         * 
         * @author Aaron.ffp
         * @version V1.0.0: Jsoup com.demo ITestHome.java isJSONObjectContainKey, 2015-9-3 20:51:21 Exp $
         * 
         * @param jsonObject : JSONObject
         * @param key        : key
         * 
         * @return boolean
         */
        public boolean isJSONObjectContainKey(JSONObject jsonObject, String key){
            boolean flag = false;
            
            try {
                if (jsonObject == null) {
                    throw new NullPointerException("The first argument {" + jsonObject + "} is null, please check this!");
                }
                
                // assert key_value : null, empty, whitespace
                if (StringUtil.isBlank(key)) {
                    this.message = "The second argument {" + key + "} is invalid, please check this!";
                    this.logger.warn(this.message);
                    
                    throw new IllegalArgumentException(this.message);
                }
                
                jsonObject.get(key);
                
                flag = true;
            } catch (Exception e) {
                this.message = e.getMessage();
                this.logger.error(this.message);
            }
            
            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;
            }
        }
    }
    

    执行结果如下图所示:

     

    至此, Java学习-031-JSON 之五 -- 特定数据获取(JSONObject满足特定键值) 顺利完结,希望此文能够给初学 JSON 的您一份参考。

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

     

  • 相关阅读:
    【题解】 bzoj2748 [HAOI2012]音量调节 (动态规划)
    【题解】 bzoj1190: [HNOI2007]梦幻岛宝珠 (动态规划)
    【题解】 bzoj1864: [Zjoi2006]三色二叉树 (动态规划)
    【题解】 [ZJOI2006]书架 (Splay)
    【题解】 [HNOI2004]宠物收养场(Splay)
    【题解】 [HNOI2002]营业额统计 (Splay)
    【题解】 [ZJOI2008] 泡泡堂(贪心/二分图/动态规划)
    【题解】 [SDOI2009] Elaxia的路线(最短路+拓扑排序)
    Aptana Studio 3 如何汉化,实现简体中文版
    js中获得当前时间是年份和月份
  • 原文地址:https://www.cnblogs.com/fengpingfan/p/4807186.html
Copyright © 2020-2023  润新知