引入 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