1. JSONPath介紹
官網地址: https://github.com/alibaba/fastjson/wiki/JSONPath
fastjson 1.2.0之后的版本支持JSONPath。這是一個很強大的功能,可以在java框架中當作對象查詢語言(OQL)來使用。
2. API
package com.alibaba.fastjson;
public class JSONPath {
// 求值,靜態方法
public static Object eval(Object rootObject, String path);
// 計算Size,Map非空元素個數,對象非空元素個數,Collection的Size,數組的長度。其他無法求值返回-1
public static int size(Object rootObject, String path);
// 是否包含,path中是否存在對象
public static boolean contains(Object rootObject, String path) { }
// 是否包含,path中是否存在指定值,如果是集合或者數組,在集合中查找value是否存在
public static boolean containsValue(Object rootObject, String path, Object value) { }
// 修改制定路徑的值,如果修改成功,返回true,否則返回false
public static boolean set(Object rootObject, String path, Object value) {}
// 在數組或者集合中添加元素
public static boolean array_add(Object rootObject, String path, Object... values);
}
建議緩存JSONPath對象,這樣能夠提高求值的性能。
3. 支持語法
| JSONPATH | 描述 |
| </td><td>根對象,例如.name | |
| [num] | 數組訪問,其中num是數字,可以是負數。例如$[0].leader.departments[-1].name |
| [num0,num1,num2…] | 數組多個元素訪問,其中num是數字,可以是負數,返回數組中的多個元素。例如$[0,3,-2,5] |
| [start:end] | 數組范圍訪問,其中start和end是開始小表和結束下標,可以是負數,返回數組中的多個元素。例如$[0:5] |
| [start:end :step] | 數組范圍訪問,其中start和end是開始小表和結束下標,可以是負數;step是步長,返回數組中的多個元素。例如$[0:5:2] |
| [?(key)] | 對象屬性非空過濾,例如$.departs[?(name)] |
| [key > 123] | 數值類型對象屬性比較過濾,例如$.departs[id >= 123],比較操作符支持=,!=,>,>=,<,<= |
| [key = ‘123’] | 字符串類型對象屬性比較過濾,例如$.departs[name = ‘123’],比較操作符支持=,!=,>,>=,<,<= |
| [key like ‘aa%’] | 字符串類型like過濾, 例如$.departs[name like ‘sz*’],通配符只支持% 支持not like |
| [key rlike ‘regexpr’] | 字符串類型正則匹配過濾, 例如departs[name like ‘aa(.)*’], 正則語法為jdk的正則語法,支持not rlike |
| [key in (‘v0’, ‘v1’)] | IN過濾, 支持字符串和數值類型 例如: .departs[namein(′wenshao′,′Yako′)]<br/>.departs[id not in (101,102)] |
| [key between 234 and 456] | BETWEEN過濾, 支持數值類型,支持not between 例如: .departs[idbetween101and201]<br/>.departs[id not between 101 and 201] |
| length() 或者 size() | 數組長度。例如$.values.size() 支持類型java.util.Map和java.util.Collection和數組 |
| . | 屬性訪問,例如$.name |
| .. | deepScan屬性訪問,例如$..name |
| * | 對象的所有屬性,例如$.leader.* |
| [‘key’] | 屬性訪問。例如$[‘name’] |
| [‘key0’,’key1’] | 多個屬性訪問。例如$[‘id’,’name’] |
以下兩種寫法的語義是相同的:
$.store.book[0].title
和
$['store']['book'][0]['title']
4. 語法示例
| JSONPath | 語義 |
| $ | 根對象 |
| $[-1] | 最后元素 |
| $[:-2] | 第1個至倒數第2個 |
| $[1:] | 第2個之后所有元素 |
| $[1,2,3] | 集合中1,2,3個元素 |
5. API 示例
5.1 例1
public void test_entity() throws Exception {
Entity entity = new Entity(123, new Object());
Assert.assertSame(entity.getValue(), JSONPath.eval(entity, "$.value"));
Assert.assertTrue(JSONPath.contains(entity, "$.value"));
Assert.assertTrue(JSONPath.containsValue(entity, "$.id", 123));
Assert.assertTrue(JSONPath.containsValue(entity, "$.value", entity.getValue()));
Assert.assertEquals(2, JSONPath.size(entity, "$"));
Assert.assertEquals(0, JSONPath.size(new Object[], "$"));
}
public static class Entity {
private Integer id;
private String name;
private Object value;
public Entity() {}
public Entity(Integer id, Object value) { this.id = id; this.value = value; }
public Entity(Integer id, String name) { this.id = id; this.name = name; }
public Entity(String name) { this.name = name; }
public Integer getId() { return id; }
public Object getValue() { return value; }
public String getName() { return name; }
public void setId(Integer id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setValue(Object value) { this.value = value; }
}
5.2 例2
讀取集合多個元素的某個屬性
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("wenshao"));
entities.add(new Entity("ljw2083"));
List<String> names = (List<String>)JSONPath.eval(entities, "$.name"); // 返回enties的所有名稱
Assert.assertSame(entities.get(0).getName(), names.get(0));
Assert.assertSame(entities.get(1).getName(), names.get(1));
5.3 例3
返回集合中多個元素
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("wenshao"));
entities.add(new Entity("ljw2083"));
entities.add(new Entity("Yako"));
List<Entity> result = (List<Entity>)JSONPath.eval(entities, "[1,2]"); // 返回下標為1和2的元素
Assert.assertEquals(2, result.size());
Assert.assertSame(entities.get(1), result.get(0));
Assert.assertSame(entities.get(2), result.get(1));
5.4 例4
按范圍返回集合的子集
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("wenshao"));
entities.add(new Entity("ljw2083"));
entities.add(new Entity("Yako"));
List<Entity> result = (List<Entity>)JSONPath.eval(entities, "[0:2]"); // 返回下標從0到2的元素
Assert.assertEquals(3, result.size());
Assert.assertSame(entities.get(0), result.get(0));
Assert.assertSame(entities.get(1), result.get(1));
Assert.assertSame(entities.get(2), result.get(1));
5.5 例5
通過條件過濾,返回集合的子集
List<Entity> entities = new ArrayList<Entity>(); entities.add(new Entity(1001, "ljw2083")); entities.add(new Entity(1002, "wenshao")); entities.add(new Entity(1003, "yakolee")); entities.add(new Entity(1004, null)); List<Object> result = (List<Object>) JSONPath.eval(entities, "[id in (1001)]"); Assert.assertEquals(1, result.size()); Assert.assertSame(entities.get(0), result.get(0));
5.6 例6
根據屬性值過濾條件判斷是否返回對象,修改對象,數組屬性添加元素
Entity entity = new Entity(1001, "ljw2083"); Assert.assertSame(entity , JSONPath.eval(entity, "[id = 1001]")); Assert.assertNull(JSONPath.eval(entity, "[id = 1002]")); JSONPath.set(entity, "id", 123456); //將id字段修改為123456 Assert.assertEquals(123456, entity.getId().intValue()); JSONPath.set(entity, "value", new int[0]); //將value字段賦值為長度為0的數組 JSONPath.arrayAdd(entity, "value", 1, 2, 3); //將value字段的數組添加元素1,2,3
5.7 例7
Map root = Collections.singletonMap("company", //
Collections.singletonMap("departs", //
Arrays.asList( //
Collections.singletonMap("id",1001), //
Collections.singletonMap("id",1002), //
Collections.singletonMap("id", 1003) //
) //
));
List<Object> ids = (List<Object>) JSONPath.eval(root, "$..id");
assertEquals(3, ids.size());
assertEquals(1001, ids.get(0));
assertEquals(1002, ids.get(1));
assertEquals(1003, ids.get(2));
具體用例測試請看下面:
/**
* @author itguang
* @create 2017-12-10 10:03
**/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class JSONpathControllerTest {
@Test
public void test() {
User user = new User("itguang", "123456", "123@qq.com");
String username = (String) JSONPath.eval(user, "$.username");
log.info("$.username = {}", username);
Entity entity = new Entity(123, user);
User user1 = (User) JSONPath.eval(entity, "$.value");
log.info("user={}", user1.toString());
}
@Test
public void test2() {
User user = new User("itguang", "123456", "123@qq.com");
Entity entity = new Entity(123, user);
//判斷entity中是否有 data
boolean contains = JSONPath.contains(entity, "$.data");
Assert.assertTrue(contains);
//判斷 entity.data.username 屬性值是否為 itguang
boolean containsValue = JSONPath.containsValue(entity, "$.data.username", "itguang");
Assert.assertTrue(containsValue);
Assert.assertEquals(2, JSONPath.size(entity, "$"));
}
@Test
public void test3() {
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("邏輯"));
entities.add(new Entity("葉文傑"));
entities.add(new Entity("程心"));
//返回集合中多個元素
List<String> names = (List<String>) JSONPath.eval(entities, "$.name");
log.info("返回集合中多個元素names={}", names);
//返回下標 0 和 2 的元素
List<Entity> result = (List<Entity>) JSONPath.eval(entities, "[0,2]");
log.info("返回下標 0 和 2 的元素={}", result);
// 返回下標從0到2的元素
List<Entity> result2 = (List<Entity>) JSONPath.eval(entities, "[0:2]");
log.info("返回下標從0到2的元素={}", result2);
}
@Test
public void test4() {
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity(1001, "邏輯"));
entities.add(new Entity(1002, "程心"));
entities.add(new Entity(1003, "葉文傑"));
entities.add(new Entity(1004, null));
//通過條件過濾,返回集合的子集
List<Entity> result = (List<Entity>) JSONPath.eval(entities, "[id in (1001)]");
log.info("通過條件過濾,返回集合的子集={}", result);
}
/**
* 使用JSONPrase 解析JSON字符串或者Object對象
* <p>
* read(String json, String path)//直接使用json字符串匹配
* <p>
* eval(Object rootObject, String path) //直接使用 對象匹配
* <p>
* <p>
* {"store":{"bicycle":{"color":"red","price":19.95},"book":[{"author":"Nigel Rees","price":8.95,"category":"reference","title":"Sayings of the Century"},{"author":"Evelyn Waugh","price":12.99,"isbn":"0-553-21311-3","category":"fiction","title":"Sword of Honour"}]}}
*/
@Test
public void test5() {
String jsonStr = "{\n" +
" \"store\": {\n" +
" \"bicycle\": {\n" +
" \"color\": \"red\",\n" +
" \"price\": 19.95\n" +
" },\n" +
" \"book\": [\n" +
" {\n" +
" \"author\": \"劉慈欣\",\n" +
" \"price\": 8.95,\n" +
" \"category\": \"科幻\",\n" +
" \"title\": \"三體\"\n" +
" },\n" +
" {\n" +
" \"author\": \"itguang\",\n" +
" \"price\": 12.99,\n" +
" \"category\": \"編程語言\",\n" +
" \"title\": \"go語言實戰\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
JSONObject jsonObject = JSON.parseObject(jsonStr);
log.info(jsonObject.toString());
//得到所有的書
List<Book> books = (List<Book>) JSONPath.eval(jsonObject, "$.store.book");
log.info("books={}", books);
//得到所有的書名
List<String> titles = (List<String>) JSONPath.eval(jsonObject, "$.store.book.title");
log.info("titles={}", titles);
//第一本書title
String title = (String) JSONPath.read(jsonStr, "$.store.book[0].title");
log.info("title={}", title);
//price大於10元的book
List<Book> list = (List<Book>) JSONPath.read(jsonStr, "$.store.book[price > 10]");
log.info("price大於10元的book={}",list);
//price大於10元的title
List<String> list2 =(List<String>) JSONPath.read(jsonStr, "$.store.book[price > 10].title");
log.info("price大於10元的title={}",list2);
//category(類別)為科幻的book
List<Book> list3 = (List<Book>) JSONPath.read(jsonStr,"$.store.book[category = '科幻']");
log.info("category(類別)為科幻的book={}",list3);
//bicycle的所有屬性值
Collection<String> values = (Collection<String>) JSONPath.eval(jsonObject, "$.store.bicycle.*");
log.info("bicycle的所有屬性值={}",values);
//bicycle的color和price屬性值
List<String> read =(List<String>) JSONPath.read(jsonStr, "$.store.bicycle['color','price']");
log.info("bicycle的color和price屬性值={}",read);
}
}
源碼地址: https://github.com/itguang/gitbook-smile/blob/master/springboot-fastjson/fastjson%E4%B9%8BJSONPath%E4%BD%BF%E7%94%A8.md
轉自:http://blog.csdn.net/itguangit/article/details/78764212

