[英]Optional JsonPath using Jayway
題:
我有一個服務,它接受一個JSON
字符串作為輸入。 每次某些字段並不總是存在時, JSON
模式就不同了。 如何在使用Jayway的JsonPath
時查詢這些字段的值?
我嘗試過的:
我使用了Option.DEFAULT_PATH_LEAF_TO_NULL
作為Jayway的自述頁面解釋
Configuration config = Configuration.defaultConfiguration()
.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
if (JsonPath.isPathDefinite(attribute.jsonPath))
{
String value = JsonPath.using(config).parse(currentTx).read(attribute.jsonPath);
if (value != null)
{
attributeValues.add(value);
}
}
else
{
List<String> attributeValuesArray = JsonPath.using(config).parse(currentTx).read(attribute.jsonPath);
for (String value : attributeValuesArray)
{
if (value != null)
{
attributeValues.add(value);
}
}
}
如果找不到路徑,這應該使JsonPath.read()
返回null
,但是我的代碼仍會拋出:
com.jayway.jsonpath.PathNotFoundException:路徑$ ['somepath']中缺少屬性
當我給它一條不存在的道路時。 有誰知道這可能導致什么?
我意識到我做錯了什么。 DEFAULT_PATH_LEAF_TO_NULL
選項僅處理葉節點。 例如:
示例Json
{
"foo":{
"bar":"value"
}
}
如果查詢$.foo.tmp
,則JsonPath將返回null
因為tmp被假定為葉節點。
如果查詢$.tmp.tmp2
,JsonPath將拋出一個
com.jayway.jsonpath.PathNotFoundException,因為tmp不是葉子而且不存在。
為了繞過這個,應該使用Option.SUPPRESS_EXCEPTIONS
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.