java jsonpath分装
时间: 2023-09-28 21:06:49 浏览: 48
JSONPath是一种用于从JSON文本中提取数据的表达式语言。Java中有很多第三方库可以用来解析JSON,其中包括了JSONPath的实现。下面是一个简单的JSONPath的使用示例:
```
String json = "{ \"store\": { \"book\": [ { \"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95 }, { \"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99 }, { \"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99 }, { \"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99 } ], \"bicycle\": { \"color\": \"red\", \"price\": 19.95 } } }";
List<String> authors = JsonPath.read(json, "$.store.book[*].author");
```
上面的代码中,使用JsonPath库读取了JSON字符串中的所有作者的名字,并将它们存储在一个List对象中。可以看出,JsonPath库的使用非常简单,只需要提供JSON文本和表达式即可获取所需的数据。
如果需要将JsonPath库进行封装,可以创建一个JsonPathUtil类,包含各种常用的JsonPath表达式,以及相应的方法来获取数据。例如,可以创建一个getAuthors()方法来获取JSON字符串中所有书籍的作者:
```
public class JsonPathUtil {
public static List<String> getAuthors(String json) {
return JsonPath.read(json, "$.store.book[*].author");
}
// 其他方法...
}
```
这样就可以在应用程序中使用JsonPathUtil.getAuthors()方法来获取JSON字符串中所有的作者了。