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;
    }

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

扫描二维码关注公众号,回复: 5631141 查看本文章

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

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}

猜你喜欢

转载自www.cnblogs.com/111testing/p/10585061.html
今日推荐