日常中我们经常需要进行json 数据类型的处理,jmespath 是一个很不错的选择,简单强大,以下是关于java代码
集成的使用(一个简单示例,进行multiselect 的处理)
参考使用
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dalong</groupId>
<artifactId>myjmespath</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>io.burt</groupId>
<artifactId>jmespath-jackson</artifactId>
<version>0.5.0</version>
</dependency>
</dependencies>
</project>
- java 代码
package com.dalong;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.burt.jmespath.Expression;
import io.burt.jmespath.JmesPath;
import io.burt.jmespath.jackson.JacksonRuntime;
import java.io.IOException;
public class Application {
private static final ObjectMapper oj =new ObjectMapper();
public static void main(String[] args) throws IOException {
String info = "[
" +
" {
" +
" "name":"dalong",
" +
""age":22,
" +
""version":"v1"
" +
"},
" +
"{
" +
" "name":"dalongrong",
" +
""age":221,
" +
""version":"v2"
" +
"}
" +
"]";
JmesPath<JsonNode> jmespath = new JacksonRuntime();
Expression<JsonNode> expression = jmespath.compile("[].{Name:name,Age:age,Version:version,Type:'mydemp'}");
JsonNode input = oj.readTree(info);
JsonNode result = expression.search(input);
System.out.println(result);
}
}
- 效果
说明
jmespath 是一个很强大的json 处理指南,很值得学习下,具体可以参考jmespath 官方文档,当然aws 也提供了一个java 的包装,也是可以使用的(比较活跃)
参考资料
https://github.com/burtcorp/jmespath-java
https://github.com/aws/aws-sdk-java/tree/master/jmespath-java
http://jmespath.org/