Java Learning -031-json--specific data acquisition (Jsonobject satisfies specific key values)

Source: Internet
Author: User
Tags getmessage throw exception testng

Some of the previous posts are about JSON overview, simple data acquisition, encapsulating Cssselector data acquisition methods, and whether Jsonobject contains Key_value, please read the relevant blog post yourself.

During routine interface test scripting, it is often necessary to obtain the values of other properties corresponding to the conditional matching data based on a specific condition. For example, in the interface test script that validates the order information, we first need to obtain the order list, then find the corresponding order by the order number, and then obtain the payment amount, distribution information and other data of the order, and of course, we can obtain the order information directly, and then obtain the corresponding data. This article mainly describes the first case, when the request response contains a number of similar data information lists, how to obtain a jsonobject that satisfies a specific key_value and obtain the corresponding key corresponding value.

Directly on the source:

/** * 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 Itesth    ome {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.jav A 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"). Userag        ENT ("Jsoup demo"). Cookie ("User", "Jsoup"). Timeout (.). get ();    This.test = Doc.select ("Body"). Get (0). text (); }/** * * * @author AARON.FFP * @version v1.0.0:jsoup com.demo Itesthome.java test_getjsonob        JECTITEMTEXTUSEKV, 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: Star";                String key = "Picurl"; if (this.isjsonobjectcontainkv (Jo, Key_value)) {this.message = Key_value +--+ This.getjsonobjectitem                        TEXTUSEKV (Jo, Key_value, key) + "\ n";        System.out.println (This.message); } else {this.message = "{" + Key_value + "} not macth the Jsonobject"+ jo.tostring () +" \ n ";        System.out.println (This.message);        } key_value = "title: Van Fongping-Blog Park"; if (this.isjsonobjectcontainkv (Jo, Key_value)) {this.message = Key_value +--+ This.getjsonobjectitem                        TEXTUSEKV (Jo, Key_value, key) + "\ n";        System.out.println (This.message);                        } else {this.message = "{" + Key_value + "} not macth the Jsonobject" + jo.tostring () + "\ n";        System.out.println (This.message);        } key_value = "Van Fongping: Blog Park"; if (this.isjsonobjectcontainkv (Jo, Key_value)) {this.message = Key_value +--+ This.getjsonobjectitem                        TEXTUSEKV (Jo, Key_value, key) + "\ n";        System.out.println (This.message);                        } else {this.message = "{" + Key_value + "} not macth the Jsonobject" + jo.tostring () + "\ n";        System.out.println (This.message); } kEy_value = "Title: Camera September issuing voucher"; if (this.isjsonobjectcontainkv (Jo, Key_value)) {this.message = Key_value +--+ This.getjsonobjectitem                        TEXTUSEKV (Jo, Key_value, key) + "\ n";        System.out.println (This.message);                        } else {this.message = "{" + Key_value + "} not macth the Jsonobject" + jo.tostring () + "\ n";        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        : + EXP $ * * @param jsonobject:jsonobject * @param key_value:key and value * @param key : Key * * @return String */public string getjsonobjectitemtextusekv (Jsonobject jsonobject, String key_val        UE, String key) {if (Jsonobject = = null) {return ""; } if (STRINGUTIL.ISBLank (key_value) | | Stringutil.isblank (key)) {This.message = "The argument {" + Key_value + "} must is 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, ple            ASE 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:json Object * @param kv:key:value * * @return Boolean */public boolean isjsonobjectcontainkv (JSO        Nobject 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 {" + Jsonobjec            T + "} 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 = TR                Ue                }} 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 keyis 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 */Pub                Lic boolean Isjsonobjectcontainkey (Jsonobject jsonobject, String key) {Boolean flag = false; try {if (Jsonobject = = null) {throw new NullPointerException ("the first argument {" + Jsonobje            CT + "} 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 * @ve Rsion v1.0.0:jsoup com.demo Itesthome.java getjsontext, 2015-9-1 19:40:12 Exp $ * * @param json:json Strin G * @param selector:json selector * $key | $key | #array | #int | $int |key * #key | #int * $k        ey| #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 is null if (JSON = = NULL | | selector = = NULL) {This.message = "The argument {" + JS            On + "} and {" + selector + "} must is 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")) {J                    o = 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; }    }}

The execution results are as follows:

At this point, Java Learning -031-json Five-specific data acquisition (Jsonobject to meet specific key values) The smooth end, I hope this article can give you a reference to the JSON.

Finally, very grateful to the pro-stop, I hope this article can be pro helpful. Warmly welcome the kiss to discuss together and progress together. Thank you so much! ^_^

Java Learning -031-json--specific data acquisition (Jsonobject satisfies specific key values)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.