前文對獲取 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("\n\n==================================== 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 的您一份參考。
最后,非常感謝親的駐足,希望此文能對親有所幫助。熱烈歡迎親一起探討,共同進步。非常感謝! ^_^
