场景: 发送接口请求后,得到请求结果值是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数据中的值的更多相关文章

  1. Java如何获取JSON数据中的值

    场景:在接口自动化场景中,下个接口发送的请求参数,依赖上个接口请求结果中的值.需要将获取值作为全局参数引用. import java.io.File; import java.io.FileInput ...

  2. js 获取json串中的值

    用js中著名的eval函数var strJSON = "{name:'json name'}";//得到的JSONvar obj = eval( "(" + s ...

  3. java获取json格式中的值

    先右键项目,然后点击properties,然后选中java Builder Path,选择add external jars,引入需要引入json.jar package web; import or ...

  4. C#调用接口返回json数据中含有双引号 或其他非法字符的解决办法

    这几天,调用别人接口返回json数据含有特殊符号(双引号),当转换成json对象总是报错, json字符格式如下 { "BOXINFO":[ { ", "ITE ...

  5. ajax获取json数据为undefined--原因解析

    解决办法:var dataObj=eval("("+data+")");//转换为json对象 问题: 1. 碰到一个问题ajax成功获取json数据后,取值显 ...

  6. 获取JSON对象的属性值

    1.问题背景 有一个json对象,其中有键值对,那怎样获取json对象中属性值 2.实现源码 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...

  7. mysql json_extract函数获取json字段中某个key的值

    参考:https://www.cnblogs.com/chuanzhang053/p/9139624.html json_extract函数可以获取json对象中指定key的值,用法:json_ext ...

  8. Netflix Falcor获取JSON数据

    Netflix开源了JavaScript库Falcor,它为从多个来源获取JSON数据提供了模型和异步机制. Netflix利用Falcor库实现通过JSON数据填充他们网页应用的用户界面.所有来自内 ...

  9. jquery通过ajax方法获取json数据不执行success

    1.jquery通过ajax方法获取json数据不执行success回调 问题描述:jquery通过ajax方法获取json数据不执行success回调方法 问题原因:json格式存在问题或不符合标准 ...

随机推荐

  1. 将DataTable转换为List<T>对象遇到问题:类型“System.Int64”的对象无法转换为类型“System.Int32”。

    可以利用反射将DataTable转换为List<T>对象:原始链接http://www.jb51.net/article/67386.htm 但是该方法在DataTable里某个字段类型是 ...

  2. Deepin debian安装Libreoffice

    Libreoffice LibreOffice 是一款功能强大的办公软件,默认使用开放文档格式 (OpenDocument Format , ODF), 并支持 .docx, .xlsx, *.ppt ...

  3. linux磁盘阵列 逻辑卷管理器

    Difficult doesn't mean impossible.It simply meansthat you have to work hard.困难并不代表不可能,它仅仅意味着你必须努力奋斗. ...

  4. SpringBoot 集成数据库连接池Druid

    1.pom.xml依赖 <dependency> <groupId>com.alibaba</groupId> <artifactId>druid< ...

  5. 解决使用maven的java web项目导入后出现的有关问题 -cannot be read or is not a valid ZIP file

    解决使用maven的java web项目导入后出现的有关问题 -cannot be read or is not a valid ZIP file   错误问题:虽然查找repository目录下是有 ...

  6. [CF662C] Binary Table(FWT)

    题意: https://www.cnblogs.com/cjyyb/p/9065801.html 题解:

  7. Yii2中mongodb使用ActiveRecord的数据操作

    概况  Yii2 一个高效安全的高性能PHP框架.mongodb 一个高性能分布式文档存储NOSQL数据库. 关于mongodb与mysql的优缺点,应该都了解过. mysql传统关系数据库,安全稳定 ...

  8. UOJ#110. 【APIO2015】Bali Sculptures 贪心 动态规划

    原文链接https://www.cnblogs.com/zhouzhendong/p/UOJ110.html 题解 我们发现n=2000 的子任务保证A=1! 分两种情况讨论: $n\leq 100$ ...

  9. Ubuntu16.04下Hadoop的本地安装与配置

    一.系统环境 os : Ubuntu 16.04 LTS 64bit jdk : 1.8.0_161 hadoop : 2.6.4 部署时使用的用户名为hadoop,下文中需要使用用户名的地方请更改为 ...

  10. 蓝桥杯 购物单(使用word协助)

    标题: 购物单 小明刚刚找到工作,老板人很好,只是老板夫人很爱购物.老板忙的时候经常让小明帮忙到商场代为购物.小明很厌烦,但又不好推辞. 这不,XX大促销又来了!老板夫人开出了长长的购物单,都是有打折 ...