JsonPath如何获取JSON数据中的值
场景: 发送接口请求后,得到请求结果值是Json数据, 需要从Json数据信息中提取字段值。
响应值字符与字符之间有空格,导致用正则表达式方法提取比较麻烦,于是用java的JsonPath方法提取快速方便好用,根据JSON路径去取。
Json数据: 需要提取FILE 字段对应的值。
{
"data" : {
"testCaseData" : [
{
"agent_version" : "9.7.0.2225",
"android_id" : "e3d699cf01620531",
"asset_number" : "",
"FILE" : "./ wwwccko(33) .zip",
"noncomp_reason" : "",
},
{
"agent_version" : "2.0.0.1518",
"android_id" : "",
"asset_number" : "",
"FILE" : "./XXXX(22) .zip",
"noncomp_reason" : "",
}
],
"total_count" : 2
},
"error_code" : 1,
"message" : "Success",
"timestamp" : 1504765848
}
解决方法:
package com.app.test; import java.util.LinkedHashMap;
import net.minidev.json.JSONArray;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Predicate;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException; public class TestJsonPath { public static void main(String[] args) {
String charset = "utf-8";
File file = new File("D:\\Work_Report\\JSON2.txt");
long fileByteLength = file.length();
byte[] content = new byte[(int) fileByteLength];
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
fileInputStream.read(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String str = null;
try {
str = new String(content, charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(str);
readjson(str, "$.data.testCaseData[0].FILE");
System.out.println(readjson(str, "$.data.testCaseData[0].FILE"));
} public static String readjson(String json, String jsonPath) {
try {
Object value = JsonPath.read(json, jsonPath, new Predicate[0]);
if (value instanceof Integer) {
return value.toString();
} else if (value instanceof String) {
return value.toString();
} else if (value instanceof Boolean) {
return value.toString();
} else if (value instanceof JSONArray) {
JSONArray arr = (JSONArray) value;
if (!arr.isEmpty()) {
return arr.toJSONString();
} else
return "";
} else if (value instanceof LinkedHashMap) {
return value.toString();
} else if (value instanceof Float) {
return value.toString();
} else {
return value.toString();
}
} catch (Exception e) {
return "pathnotfound";
}
}
}
注: JsonPath固定语法: $.XX.XX[索引].对象key
依赖包
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
String rep.jsonpath.result;
rep=repv.getResponseDataAsString();
jsonpath = "$.data.device[1].version
result = readjson(pre,jsonpath)
vars.put("XX",result)
工具类:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;
import net.minidev.json.JSONArray;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Predicate; public class Utils { public static String readJson(String filePath) {
String charset = "utf-8";
File file = new File(filePath);
long fileByteLength = file.length();
byte[] content = new byte[(int) fileByteLength];
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
fileInputStream.read(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String str = null;
try {
str = new String(content, charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
} public static String readjson(String json, String jsonPath) {
try {
Object value = JsonPath.read(json, jsonPath, new Predicate[]);
if (value instanceof Integer) {
return value.toString();
} else if (value instanceof String) {
return value.toString();
} else if (value instanceof Boolean) {
return value.toString();
} else if (value instanceof JSONArray) {
JSONArray arr = (JSONArray) value;
if (!arr.isEmpty()) {
return arr.toJSONString();
} else
return "";
} else if (value instanceof LinkedHashMap) {
return value.toString();
} else if (value instanceof Float) {
return value.toString();
} else {
return value.toString();
}
} catch (Exception e) {
return "pathnotfound";
}
} }
JsonPath如何获取JSON数据中的值的更多相关文章
- Java如何获取JSON数据中的值
场景:在接口自动化场景中,下个接口发送的请求参数,依赖上个接口请求结果中的值.需要将获取值作为全局参数引用. import java.io.File; import java.io.FileInput ...
- js 获取json串中的值
用js中著名的eval函数var strJSON = "{name:'json name'}";//得到的JSONvar obj = eval( "(" + s ...
- java获取json格式中的值
先右键项目,然后点击properties,然后选中java Builder Path,选择add external jars,引入需要引入json.jar package web; import or ...
- C#调用接口返回json数据中含有双引号 或其他非法字符的解决办法
这几天,调用别人接口返回json数据含有特殊符号(双引号),当转换成json对象总是报错, json字符格式如下 { "BOXINFO":[ { ", "ITE ...
- ajax获取json数据为undefined--原因解析
解决办法:var dataObj=eval("("+data+")");//转换为json对象 问题: 1. 碰到一个问题ajax成功获取json数据后,取值显 ...
- 获取JSON对象的属性值
1.问题背景 有一个json对象,其中有键值对,那怎样获取json对象中属性值 2.实现源码 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...
- mysql json_extract函数获取json字段中某个key的值
参考:https://www.cnblogs.com/chuanzhang053/p/9139624.html json_extract函数可以获取json对象中指定key的值,用法:json_ext ...
- Netflix Falcor获取JSON数据
Netflix开源了JavaScript库Falcor,它为从多个来源获取JSON数据提供了模型和异步机制. Netflix利用Falcor库实现通过JSON数据填充他们网页应用的用户界面.所有来自内 ...
- jquery通过ajax方法获取json数据不执行success
1.jquery通过ajax方法获取json数据不执行success回调 问题描述:jquery通过ajax方法获取json数据不执行success回调方法 问题原因:json格式存在问题或不符合标准 ...
随机推荐
- gcc 8.2.1 / MCF thread 简介
gcc 8.2.1 下载 地址 https://gcc-mcf.lhmouse.com/ MCF threadhttps://github.lhmouse.com/ MCF thread 简介MCF ...
- CKEditor5 + vue2.0 自定义图片上传、highlight、字体等用法
因业务需求,要在 vue2.0 的项目里使用富文本编辑器,经过调研多个编辑器,CKEditor5 支持 vue,遂采用.因 CKEditor5 文档比较少,此处记录下引用和一些基本用法. CKEdit ...
- PyMysql的LIKE查询%问题
今天写一个模糊匹配的接口的时候,发现PyMysql的防注入方式会将%给转义,就算是写两个%%也是无用,依旧查不出来结果 Google翻了,Baidu翻了,一样没有适用的解决方法. 后来灵机一动想到了方 ...
- java---- XMLEncoder 和 XMLDecoder 和 xSteam工具使用
XMLEncoder: 将对象写入XML数据中 import org.dom4j.DocumentException; import java.beans.XMLEncoder; import jav ...
- Excel 恢复默认行高、列宽
操作系统:Windows 10 x64 工具1:Excel 乱糟糟的! 选中需要调整的区域,选择菜单:开始 > 格式 > 自动调整行高 选中需要调整的区域,选择菜单:开始 > 格式 ...
- EurekaClient项目启动报错Invocation of destroy method failed on bean with name 'scopedTarget.eurekaClient': org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'e
Disconnected from the target VM, address: '127.0.0.1:51233', transport: 'socket' Eureka Client的使用 使用 ...
- python之配置日志的三种方式
以下3种方式来配置logging: 1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数: 2)创建一个日志配置文件,然后使用fileCo ...
- 金蝶K/3 审批相关SQL语句
金蝶K/3 审批相关SQL语句 --http://127.0.0.1/lightApp/todocheckTask.aspx?AccID=84&&FClasstypeID=1071&a ...
- 数字滚动特效 NumScroll
1.使用前先引入jquery2.前端学习群:814798690 下载地址 https://github.com/chaorenzeng/jquery.numscroll.js.git 快速使用 1.引 ...
- Python调用selenium
import time from selenium import webdriver from selenium.webdriver.common.touch_actions import Touch ...