使用JsonPath直接从JSON创建Java对象

huangapple go评论60阅读模式
英文:

Create Java objects more directly from JSON with JsonPath

问题

List<String> httpList = JsonPath.read(json, "$.*.http_url_to_repo");
List<String> idList = JsonPath.read(json, "$.*.id");

List<GitlabProject> back = IntStream.range(0, httpList.size())
    .mapToObj(i -> new GitlabProject(httpList.get(i), idList.get(i)))
    .collect(Collectors.toList());
英文:

I create Objects from JsonPath with

List&lt;String&gt; httpList = JsonPath.read(json, &quot;$.*.http_url_to_repo&quot;);
List&lt;String&gt; idList = JsonPath.read(json, &quot;$.*.id&quot;);

for (int i = 0; i &lt; httpList.size(); i++)
{
    back.add(new GitlabProject(httpList.get(i), idList.get(i)));
}

Is there a more direct way to create the GitlabProject objects from the JSON?

The JSON looks like

[
    {
        &quot;id&quot;: 63,
        &quot;description&quot;: null,
        &quot;name&quot;: &quot;conti-maven-plugin-mm&quot;,
        &quot;name_with_namespace&quot;: &quot;ik / spu / other / conti-maven-plugin-mm&quot;,
        &quot;path&quot;: &quot;conti-maven-plugin-mm&quot;,
        &quot;path_with_namespace&quot;: &quot;ik/spu/other/conti-maven-plugin-mm&quot;,
        &quot;created_at&quot;: &quot;2023-01-30T12:33:59.218Z&quot;,
        &quot;default_branch&quot;: &quot;main&quot;,
        &quot;tag_list&quot;: [],
        &quot;topics&quot;: [],
        &quot;ssh_url_to_repo&quot;: &quot;git@gitlab-test.continentale.loc:ik/spu/other/conti-maven-plugin-mm.git&quot;,
        &quot;http_url_to_repo&quot;: &quot;https://gitlab-test.continentale.loc/ik/spu/other/conti-maven-plugin-mm.git&quot;,
        &quot;web_url&quot;: &quot;https://gitlab-test.continentale.loc/ik/spu/other/conti-maven-plugin-mm&quot;,
        ....

答案1

得分: 1

假设你的POJO具有不同的属性名称:

public class GitlabProject {
    private int id;
    @JsonProperty("http_url_to_repo")
    private String httpUrlToRepo;
    // 省略构造函数、getter和setter
}

使用Jackson库中的ObjectMapper将JSON数组反序列化为GitlabProject对象列表:

ObjectMapper objectMapper = new ObjectMapper();
List<GitlabProject> projects = objectMapper.readValue(json, new TypeReference<List<GitlabProject>>(){});

你也可以使用Google的GSON库来执行类似的操作:

List<GitlabProject> projects = new Gson().fromJson(json, new TypeToken<List<GitlabProject>>(){}.getType());

请注意,在这种情况下,如果属性名称不同,你需要使用@SerializedName

英文:

Assuming your POJO has different property names:

public class GitlabProject {
    private int id;
    @JsonProperty(&quot;http_url_to_repo&quot;)
    private String httpUrlToRepo;
    // Constructor, getters and setters omitted for brevity
}

Use ObjectMapper from the Jackson library to deserialize the JSON array into a list of GitlabProject objects:

ObjectMapper objectMapper = new ObjectMapper();
List&lt;GitlabProject&gt; projects = objectMapper.readValue(json, new TypeReference&lt;List&lt;GitlabProject&gt;&gt;(){});

You can do similar thing using Google's GSON library.

List&lt;GitlabProject&gt; projects = new Gson().fromJson(json, new TypeToken&lt;List&lt;GitlabProject&gt;&gt;(){}.getType());

Not that you'll need to use @SerializedName if property name is different in this case.

答案2

得分: 1

这可以直接使用 JsonPath 自身完成。只需定义一个自定义映射函数。

List<GitlabProject> projects = JsonPath.parse(json)
    .read("$[*]", list -> list.stream()
        .map(obj -> {
            String httpUrl = JsonPath.read(obj, "$.http_url_to_repo");
            int id = JsonPath.read(obj, "$.id");
            return new GitlabProject(httpUrl, id);
        })
        .collect(Collectors.toList())
);
  • "$[*]" - 选择JSON数组中的所有元素。
  • "read" 方法内的 lambda 表达式从JSON中提取所有 "http_url_to_repo" 和 "id" 值,并创建相应的 "GitlabProject"。
  • 最后,使用 "Collectors.toList()" 创建对象列表。
英文:

This can be done using JsonPath itself directly.
Just define a custom mapping function.

List&lt;GitlabProject&gt; projects = JsonPath.parse(json)
    .read(&quot;$[*]&quot;, list -&gt; list.stream()
        .map(obj -&gt; {
            String httpUrl = JsonPath.read(obj, &quot;$.http_url_to_repo&quot;);
            int id = JsonPath.read(obj, &quot;$.id&quot;);
            return new GitlabProject(httpUrl, id);
        })
        .collect(Collectors.toList())
);
  • "$[*]" - selects all elements in the JSON array
  • The lamda expression inside "read" method extracts all
    "http_url_to_repo" and "id" values from JSON and creates
    corresponding "GitlabProject".
  • Finally the list of objects are created using
    "Collectors.toList()"

huangapple
  • 本文由 发表于 2023年2月14日 20:07:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定