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

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Java学习-030-JSON之四--判断JSONObject是否包含键值对前⽂对获取 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 = "/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 的您⼀份参考。

最后,⾮常感谢亲的驻⾜,希望此⽂能对亲有所帮助。

热烈欢迎亲⼀起探讨,共同进步。

⾮常感谢! ^_^。

相关文档
最新文档