JsonPath 调整配置

在 JsonPath 中,创建 Configuration  时,有几个 Option 选项标志可以改变默认行为。Option 可选值如下:

Option.DEFAULT_PATH_LEAF_TO_NULL

该选项使 JsonPath 在缺少叶时返回空值。请看下面的 json:

[
   {
      "name" : "john",
      "gender" : "male"
   },
   {
      "name" : "ben"
   }
]

示例代码:

package com.hxstrive.json_path.config;

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Option;

/**
 * JsonPath 配置
 * @author hxstrive.com
 */
public class ConfigDemo1 {

    public static void main(String[] args) {
        String json = "[" +
                "   {" +
                "      \"name\" : \"john\"," +
                "      \"gender\" : \"male\"" +
                "   }," +
                "   {" +
                "      \"name\" : \"ben\"" +
                "   }" +
                "]";

        Configuration conf = Configuration.defaultConfiguration();
        // 正常工作
        String gender0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
        System.out.println("gender0: "+ gender0);
        try {
            // 抛出 PathNotFoundException 异常
            String gender1 = JsonPath.using(conf).parse(json).read("$[1]['gender']");
            System.out.println("gender1: " + gender1);
        } catch (Exception e) {
            System.out.println("Caught exception: "+ e.getMessage());
        }

        Configuration conf2 = conf.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
        // 正常工作
        gender0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
        System.out.println("gender0: "+ gender0);

        // 正常工作,但是返回 null
        String gender1 = JsonPath.using(conf2).parse(json).read("$[1]['gender']");
        System.out.println("gender1: " + gender1);
    }

}

运行示例,输出如下:

gender0: male
Caught exception: No results for path: $[1]['gender']
gender0: male
gender1: null

Option.ALWAYS_RETURN_LIST

该选项可将 JsonPath 配置为返回列表,即使路径是确定的。示例:

package com.hxstrive.json_path.config;

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Option;
import java.util.List;


/**
 * JsonPath 配置
 * @author hxstrive.com
 */
public class ConfigDemo2 {

    public static void main(String[] args) {
        String json = "[" +
                "   {" +
                "      \"name\" : \"john\"," +
                "      \"gender\" : \"male\"" +
                "   }," +
                "   {" +
                "      \"name\" : \"ben\"" +
                "   }" +
                "]";
        Configuration conf = Configuration.defaultConfiguration();
        try {
            // 抛出 ClassCastException 异常
            List<String> genders0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
            System.out.println("genders0: " + genders0);
        } catch (ClassCastException e) {
            System.out.println(e.getMessage());
        }

        Configuration conf2 = conf.addOptions(Option.ALWAYS_RETURN_LIST);
        // 正常工作
        List<String> genders0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
        System.out.println("genders0: " + genders0);
    }

}

运行示例,输出如下:

java.lang.String cannot be cast to java.util.List
genders0: ["male"]

Option.SUPPRESS_EXCEPTIONS

该选项确保路径评估不会传播异常。它遵循以下简单规则:

  • 如果存在 ALWAYS_RETURN_LIST 选项,将返回空列表。

  • 如果不存在选项 ALWAYS_RETURN_LIST,则返回空值。

当你设置 Option.SUPPRESS_EXCEPTIONS 选项时,如果 JsonPath 查询在解析或执行过程中遇到错误(例如,查询路径不正确或 JSON 文档格式错误),它不会抛出异常,而是会返回一个空的结果。这在你不想因为单个查询失败而中断整个处理流程时非常有用。

注意,虽然 Option.SUPPRESS_EXCEPTIONS 可以防止异常被抛出,但它不会修复或更正任何潜在的错误。因此,如果你的应用程序依赖于正确的查询结果,你应该确保你的查询和 JSON 数据都是有效的,而不仅仅是依赖于这个选项来避免异常。

Option.REQUIRE_PROPERTIES

该选项用于配置 JsonPath,使其在评估不确定路径时要求使用路径中定义的属性。这意味着在执行 JSONPath 查询时,如果查询没有找到指定的属性,将引发异常。这是一种用于确保查询结果包含所需属性的一种方法。

当使用 JsonPath 查询时,如果查询没有找到指定的属性,通常会返回一个空值或者抛出一个异常。Option.REQUIRE_PROPERTIES 选项允许您在查询没有找到属性时引发异常,而不是返回空值或抛出异常。这样可以确保您的代码处理查询结果时始终知道属性存在。

示例如下:

package com.hxstrive.json_path.config;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;

import java.util.List;

/**
 * JsonPath 配置
 * @author hxstrive.com
 */
public class ConfigDemo3 {

    public static void main(String[] args) {
        String json = "[" +
                "   {" +
                "      \"name\" : \"john\"," +
                "      \"gender\" : \"male\"" +
                "   }," +
                "   {" +
                "      \"name\" : \"ben\"" +
                "   }" +
                "]";
        Configuration conf = Configuration.defaultConfiguration();
        // 正常工作
        List<String> genders1 = JsonPath.using(conf).parse(json).read("$[*]['gender']");
        System.out.println("genders1=" + genders1);

        try {
            Configuration conf2 = conf.addOptions(Option.REQUIRE_PROPERTIES);
            // 抛出 PathNotFoundException 异常
            List<String> genders2 = JsonPath.using(conf2).parse(json).read("$[*]['gender']");
            System.out.println("genders2=" + genders2);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}

运行示例,输出如下:

genders1=["male"]
No results for path: $[1]['gender']  # 注意:这里明确提示了数组第二个元素没有 gender 属性


说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号