Java学习-029-JSON 之三 -- 模仿 cssSelector 封装读取 JSON 数据方法

前文简单介绍了如何通过 json-20141113.jar 提供的功能获取 JSON 的数据,敬请参阅:Java学习-028-JSON 之二 -- 数据读取

了解学习过 JQuery 的朋友都知道,JQuery 通过 cssSelector 获取页面元素对象非常简单,那么 JSON 数据的获取是否也可以如此轻松简便呢?答案是可以的。此文就此进行相应的方法封装,通过此方法可以获取 JSONObject,JSONArray,value 的字符串。对应的 cssSelector 我做出了如下的规则限定:

  1. 标示符 $:标示当前获取的对象为 JSONObject
  2. 标示符 #:标示当前获取的对象为 JSONArray
  3. 无标示符:标示当前获取的对象为 value
  4. # 标示符后必须为 $ 标识符
  5. $ 标识符后可为 $ 标识符、 # 标识符、无标识符
  6. 无标识符后不可跟任何数据

例如以下所示的 CSSSelector 表达式均为非法表达式:

     *        array|key : is illegal
     *        key|$      : is illegal
     *        key|#      : is illegal
     *        key|key   : is illegal

 

下面以易迅网首页响应数据为例演示,直接上源码了,敬请参阅。

/**
 * 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_getJsonText, 2015-9-1 20:34:18 Exp $
     *
     */
    @Test
    public void test_getJsonText(){
        System.out.println("\n==================================== test_getJsonText");
        
        System.out.println("\n result selector : errno --> " + this.getJsonText(this.test, "errno"));
        System.out.println("\n result selector : $data|#icon --> " + this.getJsonText(this.test, "$data|#icon"));
        System.out.println("\n result selector : $data|#floor|$1|#colmunInfo --> " + this.getJsonText(this.test, "$data|#floor|$1|#colmunInfo"));
        System.out.println("\n result selector : $data|#floor|$1|start_date --> " + this.getJsonText(this.test, "$data|#floor|$1|start_date"));
        System.out.println("\n result selector : $data|#floor|$1|#colmunInfo|$0 --> " + this.getJsonText(this.test, "$data|#floor|$1|#colmunInfo|$0"));
        System.out.println("\n result selector : $data|#floor|$1|#colmunInfo|$0|title --> " + this.getJsonText(this.test, "$data|#floor|$1|#colmunInfo|$0|title"));
    }
    
    /**
     * 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学习-029-JSON 之三 -- 模仿 cssSelector 封装读取 JSON 数据方法 顺利完结,希望此文能够给初学 Java 的您一份参考。

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

 

posted @ 2015-09-14 16:26  范丰平  Views(588)  Comments(0Edit  收藏  举报