如何通过JsonPath更直接地从JSON创建Java的GitlabProject对象?
更直接用JsonPath创建GitlabProject对象的方法
我当前通过以下代码提取JSON数据来构建GitlabProject对象:
List<String> httpList = JsonPath.read(json, "$.*.http_url_to_repo"); List<String> idList = JsonPath.read(json, "$.*.id"); for (int i = 0; i < httpList.size(); i++) { back.add(new GitlabProject(httpList.get(i), idList.get(i))); }
对应的JSON结构示例:
[ { "id": 63, "description": null, "name": "conti-maven-plugin-mm", "name_with_namespace": "ik / spu / other / conti-maven-plugin-mm", "path": "conti-maven-plugin-mm", "path_with_namespace": "ik/spu/other/conti-maven-plugin-mm", "created_at": "2023-01-30T12:33:59.218Z", "default_branch": "main", "tag_list": [], "topics": [], "ssh_url_to_repo": "git@gitlab-test.continentale.loc:ik/spu/other/conti-maven-plugin-mm.git", "http_url_to_repo": "https://gitlab-test.continentale.loc/ik/spu/other/conti-maven-plugin-mm.git", "web_url": "https://gitlab-test.continentale.loc/ik/spu/other/conti-maven-plugin-mm" // 其他字段省略 } ]
三种更直接的实现方式
方式1:JsonPath直接映射到对象列表
先确保GitlabProject类的字段与JSON键对应(或用@JsonProperty注解适配),然后直接读取为对象列表:// 配置Jackson作为JsonPath的反序列化器 Configuration config = Configuration.defaultConfiguration() .setProvider(new JacksonJsonProvider()); List<GitlabProject> projectList = JsonPath.using(config) .parse(json) .read("$", new TypeRef<List<GitlabProject>>() {});类定义示例(带构造函数注解):
public class GitlabProject { private String httpUrlToRepo; private String id; @JsonCreator public GitlabProject( @JsonProperty("http_url_to_repo") String httpUrlToRepo, @JsonProperty("id") String id ) { this.httpUrlToRepo = httpUrlToRepo; this.id = id; } // 可选:添加getter方法 }方式2:直接用Jackson反序列化(无需JsonPath)
如果不需要筛选字段,直接用Jackson的ObjectMapper更简洁:ObjectMapper mapper = new ObjectMapper(); List<GitlabProject> projectList = mapper.readValue( json, new TypeReference<List<GitlabProject>>() {} );方式3:JsonPath筛选特定字段后映射
若只需要id和http_url_to_repo字段,可先筛选再映射:List<GitlabProject> projectList = JsonPath.read( json, "$.*.['id', 'http_url_to_repo']", new TypeRef<List<GitlabProject>>() {} );
内容的提问来源于stack exchange,提问作者JF Meier
相关产品推荐
相关产品推荐

