• 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"));
    
      }
    
    }
  • 相关阅读:
    洛谷P3953 逛公园
    洛谷P1247 取火柴游戏
    洛谷P2024 食物链
    洛谷P2680 运输计划
    hdu 1495 非常可乐(bfs)
    poj3984 迷宫问题(简单的输出路径的bfs)
    Codeforces 729C Road to Cinema(二分)
    Codeforces Technocup 2017
    Codeforces Technocup 2017
    poj 2251 Dungeon Master(bfs)
  • 原文地址:https://www.cnblogs.com/jentary/p/15873798.html
Copyright © 2020-2023  润新知