• json路径解析


    JsonPath

    JsonPath:从多层嵌套Json中解析所需要的值

    <!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>2.4.0</version>
    </dependency>
    public class JsonUtilTest extends CommonForTest {
    
      String json = "{\"code\":200,\"msg\":\"ok\",\"list\":[{\"id\":20,\"no\":\"1000020\",\"items\":[{\"name\":\"n1\",\"price\":21,\"infos\":{\"feature\":\"\"}}]}],\"metainfo\":{\"total\":20,\"info\":{\"owner\":\"qinshu\",\"parts\":[{\"count\":13,\"time\":{\"start\":1230002456,\"end\":234001234}}]}}}";
    
      // 常用的 Json Path 可以缓存起来重用,类似正则里的 Pattern p = Pattern.compile('regexString')
      JsonPath codePath = JsonPath.compile("$.code");
      JsonPath totalPath = JsonPath.compile("$.metainfo.total");
    
      @Test
      public void testReadVal() {
    
        eq(null, JsonUtil.readVal(null, "code"));
        eq(null, JsonUtil.readVal(json, null));
        eq("200", JsonUtil.readVal(json, "code"));
        eq("20", JsonUtil.readVal(json, "metainfo.total"));
        eq("qinshu", JsonUtil.readVal(json, "metainfo.info.owner"));
        eq(null, JsonUtil.readVal("invalid json", "code"));
        eq(null,JsonUtil.readVal(json, "metainfo.extra.feature"));
    
        eq(null, JsonUtil.readValUsingJsonPath(null, "code"));
        eq(null, JsonUtil.readValUsingJsonPath(json, null));
        eq("200", JsonUtil.readValUsingJsonPath(json, "code"));
        eq("20", JsonUtil.readValUsingJsonPath(json, "metainfo.total"));
        eq("qinshu", JsonUtil.readValUsingJsonPath(json, "metainfo.info.owner"));
        eq(null, JsonUtil.readValUsingJsonPath("invalid json", "code"));
        eq(null,JsonUtil.readValUsingJsonPath(json, "metainfo.extra.feature"));
    
        eq(200, codePath.read(json));
        eq(20, totalPath.read(json));
        eq("qinshu", JsonPath.read(json, "$.metainfo.info.owner"));
        eq("n1", JsonPath.read(json, "$.list[0].items[0].name"));
        eq(13, JsonPath.read(json, "$.metainfo.info.parts[0].count"));
    
      }
    
    }
  • 相关阅读:
    layui动态修改表单form内容
    jquery-实现表单拖拽拼图验证功能
    jquery-实现省市区地址选择器三级联动
    python学习笔记(七)break 和continue
    python 学习笔记(六)for循环、for嵌套循环案例
    python学习笔记(5) while嵌套循环案例
    python学习笔记(四)if嵌套格式和案例
    Experiment
    Variational Image Compression With a Scale Hyperprior(ICLR 2018)
    Video Compression through Image Interpolation(ECCV 2018)
  • 原文地址:https://www.cnblogs.com/jentary/p/15873798.html
Copyright © 2020-2023  润新知