小编典典

您需要使用JsonPath库,该库仅允许您选择必填字段,然后可以Jackson将原始数据转换为POJO类。解决方案示例如下所示:

import com.fasterxml.jackson.annotation.JsonProperty;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.databind.type.CollectionType;

import com.jayway.jsonpath.JsonPath;

import java.io.File;

import java.util.List;

import java.util.Map;

public class JsonPathApp {

public static void main(String[] args) throws Exception {

File jsonFile = new File("./resource/test.json").getAbsoluteFile();

List nodes = JsonPath.parse(jsonFile).read("$..value[*].user.name");

ObjectMapper mapper = new ObjectMapper();

CollectionType usersType = mapper.getTypeFactory().constructCollectionType(List.class, User.class);

List users = mapper.convertValue(nodes, usersType);

System.out.println(users);

}

}

class User {

@JsonProperty("first")

private String firstName;

@JsonProperty("last")

private String lastName;

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

@Override

public String toString() {

return "User{" +

"firstName='" + firstName + '\'' +

", lastName='" + lastName + '\'' +

'}';

}

}

上面的代码打印:

[User{firstName='x', lastName='y'}]

2020-07-27

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐