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格式存在问题或不符合标准 ...
随机推荐
- sed追加文本-sed脚本追加文本
input为sed输入文件,内容如下: [root@node1 gitlab-test-]# cat inppu.txt aa bb cc dd 追加文本: 1.匹配 aa 行之后追加文本 We a ...
- HTML及CSS学习笔记
推荐博客:付铭 day-01 HTML 1.HTML 基本语法 html标签 单标签 <img /> .<img> 双标签 <html> </html> ...
- vue脚手架安装步骤vue-cli
1.环境搭建 安装node.js: 从node.js官网下载并安装node,安装过程很简单. npm 版本需要大于 3.0,如果低于此版本需要升级它: # 查看版本 $ npm -v 2.3 ...
- MySQL基础使用
数据库 其实我们常常说的数据库,应该叫数据库系统. 表和库 数据表:用来保存数据的表格 数据库:用来统一管理数据表的容器 启动mysql 关闭mysql service mysqld start(启动 ...
- Centos查看系统CPU个数、核心数、线程数
1.查看 CPU 物理个数 grep 'physical id' /proc/cpuinfo | sort -u | wc -l 2.查看 CPU 核心数量 grep 'core id' /proc/ ...
- Sass 增强语法的样式表
功能: 完全兼容CSS3 相对CSS,扩展了变量.嵌套和mixins 对控制颜色和其他值的非常有用的方法 高级功能,如库的直接控制 良好的格式,自定义输出 语法 对于Sass,有两种语法. 一种叫SC ...
- ASP.NET 多环境下配置文件web.config的灵活配置
调试,发布Asp.net程序的时候,开发环境和发布环境的Web.Config往往不同,比如connectionstring等.如果常常有调试,发布的需求,就需要常常修改web.config文件,这往往 ...
- thinkphp5调用阿里大鱼短信
:在Controller.php public function send() { if (request()->isPost()) { $phone = input('post.phone/s ...
- 02.Numpy
01.array # -*- coding: utf-8 -*- """ Numpy 패키지 특징 - 선형대수(벡터, 행렬) 연산에 효과적인 함수 제공 - lis ...
- Linux安装Tomcat-Nginx-FastDFS-Redis-Solr-集群——【第五集之补充-转载“深入理解VMware虚拟网络”】
郑重声明,此文太好,按耐不住要保存起来好好研究研究,如果侵权,联系我. 转载自王春海的http://blog.51cto.com/wangchunhai/381225,有所更改. 同时可以参考:htt ...