java 寫一個JSON解析的工具類


 

上面是一個標准的json的響應內容截圖,第一個紅圈”per_page”是一個json對象,我們可以根據”per_page”來找到對應值是3,而第二個紅圈“data”是一個JSON數組,而不是對象,不能直接去拿到里面值,需要遍歷數組。

      下面,我們寫一個JSON解析的工具方法類,如果是像第一個紅圈的JSON對象,我們直接返回對應的值,如果是需要解析類似data數組里面的json對象的值,這里我們構造方法默認解析數組第一個元素的內容。

在src/main/java下新建一個包:com.qa.util,然后在新包下創建一個TestUtil.java類。

package com.qa.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class TestUtil {
    
    /**
     * 
     * @param responseJson ,這個變量是拿到響應字符串通過json轉換成json對象
     * @param jpath,這個jpath指的是用戶想要查詢json對象的值的路徑寫法
     * jpath寫法舉例:1) per_page  2) data[1]/first_name ,data是一個json數組,[1]表示索引
     * /first_name 表示data數組下某一個元素下的json對象的名稱為first_name
     * @return, 返回first_name這個json對象名稱對應的值
     */
    
    //1 json解析方法
    public static String getValueByJPath(JSONObject responseJson, String jpath) {
        
        Object obj = responseJson;
        for(String s : jpath.split("/")) {
            if(!s.isEmpty()) {
                if(!(s.contains("[") || s.contains("]"))) {
                    obj = ((JSONObject) obj).get(s);
                }else if(s.contains("[") || s.contains("]")) {
                    obj = ((JSONArray)((JSONObject)obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("\\[")[1].replaceAll("]", "")));
                }
            }
        }
        return obj.toString();
    }

}

簡單解釋下上面的代碼,主要是查詢兩種json對象的的值,第一種最簡單的,這個json對象在整個json串的第一層,例如上面截圖中的per_page,這個per_page就是通過jpath這個參數傳入,返回的結果就是3. 第二種jpath的查詢,例如我想查詢data下第一個用戶信息里面的first_name的值,這個時候jpath的寫法就是data[0]/first_name,查詢結果應該是Eve。

======================================================================================

======================================================================================

將接口請求返回的 response 轉換成 json 格式

    /**
     * 
     * @param response, 任何請求返回返回的響應對象
     * @return, 返回響應體的json格式對象,方便接下來對JSON對象內容解析
     * 接下來,一般會繼續調用TestUtil類下的json解析方法得到某一個json對象的值
     * @throws ParseException
     * @throws IOException
     */
    public JSONObject getResponseJson (CloseableHttpResponse response) throws ParseException, IOException {
        Log.info("得到響應對象的String格式");
        String responseString = EntityUtils.toString(response.getEntity(),"UTF-8");
        JSONObject responseJson = JSON.parseObject(responseString);
        Log.info("返回響應內容的JSON格式");
        return responseJson;
    }


//對象轉換成Json字符串
//Users user = new Users("Anthony","tester");
//String userJsonString = JSON.toJSONString(user);

 

 

======================================================================================

======================================================================================

Python 用 json 將 string 、dict 互相轉換 

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

string_json = "{" \
         "\"status\": \"error\"," \
         "\"messages\": [\"Could not find resource or operation 'BZK1.MapServer' on the system.\"]," \
         "\"code\": 404" \
         "}"

print('對象:' + string_json)
print(type(json.loads(string_json)))
print('取值:' + json.loads(string_json)['status'])
print('取值:' + str(json.loads(string_json)['code']))

print('===========================================')

data1 = {'b': 789, 'c': 456, 'a': 123}
encode_json = json.dumps(data1)
print(type(encode_json))
print(encode_json)

print('===========================================')

decode_json = json.loads(encode_json)
print(type(decode_json))
print(decode_json['a'])
print(decode_json)

運行的結果如下:

對象:{"status": "error","messages": ["Could not find resource or operation 'BZK1.MapServer' on the system."],"code": 404}
<class 'dict'>
取值:error
取值:404
===========================================
<class 'str'>
{"b": 789, "c": 456, "a": 123}
===========================================
<class 'dict'>
123
{'b': 789, 'c': 456, 'a': 123}

 

======================================================================================

======================================================================================

 

    public static void main(String[] args) {

//從字符串解析JSON對象
        JSONObject obj = JSON.parseObject("{\"runoob\":\"菜鳥教程\"}"); //從字符串解析JSON數組
        JSONArray arr = JSON.parseArray("[\"菜鳥教程\",\"RUNOOB\"]\n"); //將JSON對象轉化為字符串
        String objStr = JSON.toJSONString(obj); //將JSON數組轉化為字符串
        String arrStr = JSON.toJSONString(arr); System.out.println("JSON.parseObject "+ obj); System.out.println("JSON.parseArray "+ arr); System.out.println("JSON.toJSONString "+ objStr); System.out.println("JSON.toJSONString "+ arrStr); }


輸出結果如下:

JSON.parseObject {"runoob":"菜鳥教程"}
JSON.parseArray ["菜鳥教程","RUNOOB"]
JSON.toJSONString {"runoob":"菜鳥教程"}
JSON.toJSONString ["菜鳥教程","RUNOOB"]

 

 

從 Java 變量到 JSON 格式的編碼過程如下:

public void testJson() {
    JSONObject object = new JSONObject();
    //string
    object.put("string","string");
    //int
    object.put("int",2);
    //boolean
    object.put("boolean",true);
    //array
    List<Integer> integers = Arrays.asList(1,2,3);
    object.put("list",integers);
    //null
    object.put("null",null);
​
    System.out.println(object);
}


在上例中,首先建立一個 JSON 對象,然后依次添加字符串、整數、布爾值以及數組,最后將其打印為字符串。

輸出結果如下:

{"boolean":true,"string":"string","list":[1,2,3],"int":2}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM