json-path 解析

引入 jar


        
            com.jayway.jsonpath
            json-path
            2.4.0
        
{
  "action": "/interface.service/xxx/queryBlackUserData",
  "all": "1",
  "result": {
    "count": 2,
    "tenant_count": 2,
    "records": [
      {
        "name": "张三",
        "pid": "500234199212121212",
        "mobile": "18623456789",
        "applied_at": "3",
        "confirmed_at": "5",
        "confirm_type": "overdue",
        "loan_type": 1,
        "test": "mytest",
        "all": "2"
      },
      {
        "name": "李四",
        "pid": "500234199299999999",
        "mobile": "13098765432",
        "applied_at": "1",
        "confirmed_at": "",
        "confirm_type": "overdue",
        "loan_type": 3,
        "all": "3"
      },
      {
        "name": "王五",
        "pid": "50023415464654659",
        "mobile": "1706454894",
        "applied_at": "-1",
        "confirmed_at": "",
        "confirm_type": "overdue",
        "loan_type": 3
      }
    ],
    "all": "4"
  },
  "code": 200,
  "subtime": "1480495123550",
  "status": "success",
  "ok": 3
}

json-path 代码解析

import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
public class JsonTest {

    private static String json = "";
    private static Gson gson = new GsonBuilder()
            .enableComplexMapKeySerialization()
            .setDateFormat("yyyy-M-d H:mm:ss")
            .create();

    @Before
    public void before() {
        try {
            File file = Paths.get(Thread.currentThread().getContextClassLoader().getResource("demo.json").toURI()).toFile();
            log.info("print file exits {}",file.exists());
            List readLines = Files.readLines(file, Charset.defaultCharset());
            json = readLines.stream().collect(Collectors.joining());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testReadJson() throws URISyntaxException {

        log.info("print json message {}",json);

        DocumentContext context = JsonPath.parse(json);
        // 输出姓名
        List names = (List) context.read("$.result.records[*].name");
        Optional.ofNullable((gson.toJson(names))).ifPresent(log::info);

        // 返回数组所有值
        //两种方式接收json
        List> records = context.read("$.result.records[*]");
        Optional.ofNullable(gson.toJson(records)).ifPresent(log::info);

        List personList = context.read("$.result.records[*]");
        Optional.ofNullable(gson.toJson(personList)).ifPresent(log::info);

        List nameList0and2List = context.read("$.result.records[0,2].name");
        Optional.ofNullable(gson.toJson(nameList0and2List)).ifPresent(log::info);

        // not contain last value
        List nameList0to2List = context.read("$.result.records[0:2].name");
        Optional.ofNullable(gson.toJson(nameList0to2List)).ifPresent(log::info);

        List lastTwoNames = context.read("$.result.records[-2:].name");
        Optional.ofNullable(gson.toJson(lastTwoNames)).ifPresent(log::info);

        List nameFromOne = context.read("$.result.records[1:].name");
        Optional.ofNullable(gson.toJson(nameFromOne)).ifPresent(log::info);

        List nameEndTwo = context.read("$.result.records[:3].name");
        Optional.ofNullable(gson.toJson(nameEndTwo)).ifPresent(log::info);

        personList = context.read("$.result.records[?(@.name == '李四')]");
        Optional.ofNullable(gson.toJson(personList)).ifPresent(log::info);

        personList = context.read("$.result.records[?(@.test)]");
        Optional.ofNullable(gson.toJson(personList)).ifPresent(log::info);

        List existAlllist = context.read("$..all");
        Optional.ofNullable(gson.toJson(existAlllist)).ifPresent(log::info);

        //12 以当前json的某个值为条件查询 这里ok为1 取出records数组中applied_at等于1的数组
        List ok = context.read("$.result.records[?(@.applied_at == $['ok'])]");
        Optional.ofNullable(gson.toJson(ok)).ifPresent(log::info);

        //13 正则匹配
        personList = context.read("$.result.records[?(@.pid =~ /.*999/i)]");
        Optional.ofNullable(gson.toJson(personList)).ifPresent(log::info);

        //14 多条件
        List mobile = context.read("$.result.records[?(@.all == '2' || @.name == '李四' )].mobile");
        Optional.ofNullable(gson.toJson(mobile)).ifPresent(log::info);

        //14 查询数组长度
        Integer length01 = context.read("$.result.records.length()");
        Optional.ofNullable(gson.toJson(mobile)).ifPresent(log::info);

        //15 查询list里面每个对象长度
        List length02 = context.read("$.result.records[?(@.all == '2' || @.name == '李四' )].length()");
        Optional.ofNullable(gson.toJson(length02)).ifPresent(log::info);

        //16 最大值
        double maxV = context.read("$.max($.result.records[0].loan_type,$.result.records[1].loan_type,$.result.records[2].loan_type)");
        Optional.ofNullable(gson.toJson(maxV)).ifPresent(log::info);

        //17 最小值
        double minV = context.read("$.min($.result.records[0].loan_type,$.result.records[1].loan_type,$.result.records[2].loan_type)");
        Optional.ofNullable(gson.toJson(minV)).ifPresent(log::info);

        //18 平均值
        double avgV = context.read("$.avg($.result.records[0].loan_type,$.result.records[1].loan_type,$.result.records[2].loan_type)");
        Optional.ofNullable(gson.toJson(avgV)).ifPresent(log::info);

        //19 标准差
        double stddevV = context.read("$.stddev($.result.records[0].loan_type,$.result.records[1].loan_type,$.result.records[2].loan_type)");
        Optional.ofNullable(gson.toJson(stddevV)).ifPresent(log::info);

    }
}

你可能感兴趣的:(json-path 解析)