OGNL获取嵌套json对象内的值

OGNL获取嵌套json对象内的值

柳性安 74 2023-11-15

记录一下一种能获取复杂嵌套json对象内特定值的方法,以前一般是使用递归的方式去获取。现在发现可以使用OGNL去解析,便利程度大大提高。

依赖项

<!--对象图导航语言-->
<dependency>
    <groupId>ognl</groupId>
    <artifactId>ognl</artifactId>
    <version>3.4.2</version>
</dependency>
<!--解析json数据-->
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.15.2</version>
</dependency>

工具类

public class JsonUtil {
    private final static ObjectMapper mapper = new ObjectMapper();

    public static ObjectMapper getInstance() {
        return mapper;
    }

    //解析json字符串的
    @SneakyThrows
    public static <T> T parse(String jsonStr, Class<T> clazz) {
        return getInstance().readValue(jsonStr, clazz);
    }

    //读取表达式path需求的值
    public static <T> T getValue(Map<?, ?> map, String path, Class<T> clazz) throws OgnlException {
        OgnlContext ctx = Ognl.createDefaultContext(map);
        return (T) Ognl.getValue(path, ctx, ctx.getRoot());
    }
}

测试

准备json字符串

private static String jsonStr = """
        {
          "id": "123",
          "author":  {
            "uid": "1",
            "name": "liusir"
          },
          "title": "My awesome blog post",
          "comments": {
            "total": 100,
            "result": [{
                "id": "321",
                "commenter": {
                "uid": "1",
                  "name": "ll"
                }
              },
              {
                "id": "322",
                "commenter": {
                "uid": "2",
                  "name": "ii"
                }
              },
              {
                "id": "323",
                "commenter": {
                "uid": "3",
                  "name": "uu"
                }
              }]
          }
        }
        """;

测试类

@Test
public void test(){
    Map<String,Object> map = JsonUtil.parse(jsonStr, Map.class);
    try {
        String value = JsonUtil.getValue(map, "author.name", String.class);
        System.out.println(value);
        List<String> list = JsonUtil.getValue(map, "comments.result", List.class);
        System.out.println(list.toString());
        String integer = JsonUtil.getValue(map, "comments.result[1].id", String.class);
        System.out.println(integer);
    } catch (OgnlException e) {
        System.out.println(e.getMessage());
    }
}

测试结果

liusir
[{id=321, commenter={uid=1, name=ll}}, {id=322, commenter={uid=2, name=ii}}, {id=323, commenter={uid=3, name=uu}}]
322