简体   繁体   English

如何在 Java 中使用 Jackson 对 JSON 响应进行建模?

[英]How to model JSON response with Jackson in Java?

I am try to model an Api response using Jackson.我正在尝试使用 Jackson 对 Api 响应进行建模。 The id will be the same type in all but the body will be different types. id 将是相同的类型,但主体将是不同的类型。

An example response would be:一个示例响应是:

{
    "responses": [
        {
            "id": "jobTitle",
            "body": {
                "jobTitle": "Software Engineer"
            }
        },
        {
            "id": "thumbnailPhoto",
            "body": "base 64 bit string"
        }
    ]
}

I have the following implementation.我有以下实现。 Is this the correct approach?这是正确的方法吗? If the type for body returns as a string, would the JobTitle be ignored/ null?如果 body 的类型作为字符串返回,JobTitle 会被忽略/为空吗?

@JsonIgnoreProperties(ignoreUnknown = true)
public class Response
{
  @JsonProperty("id")
  private String id;

  @JsonProperty("body")
  private String photo;

  @JsonProperty("body")
  private JobTitle jobTitle;

  // getters and setters
}

I'm no expert in this area, but I would like to share my answer here.我不是这方面的专家,但我想在这里分享我的答案。

I don't know why you design the JSON string as an array of responses for your original question.我不知道您为什么将 JSON 字符串设计为原始问题的响应数组。 I would suggest a better design to be a single instance of "Response" object as below:我建议将更好的设计作为“响应”对象的单个实例,如下所示:

{
 "id":"response id",
 "jobTitle":"title",
 "img":"img b64 string"
}

Just leave the field null if not exists.如果不存在,只需将该字段留空。

But if you insist on using the origin design, below code below coding can be achieved, but the JSON string need small changes to add "type" info Tutorial from Baeldung .但是如果你坚持使用原始设计,下面的代码可以实现,但是 JSON 字符串需要一些小的更改以添加来自 Baeldung 的“类型”信息教程

[ {
  "id" : "1",
  "body" : {
    "type" : "jobTitle",
    "jobTitle" : "job title"
  }
}, {
  "id" : "2",
  "body" : {
    "type" : "img",
    "data" : "xxxxx"
  }
} ]

Java coding as below: Java编码如下:

    package org.example.test4;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.util.ArrayList;

public class TestApp {

    public static class Response<X extends Body> {
        private String id;
        private X body;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public X getBody() {
            return body;
        }

        public void setBody(X body) {
            this.body = body;
        }
    }
    @JsonTypeInfo(
            use = JsonTypeInfo.Id.NAME,
            include = JsonTypeInfo.As.PROPERTY,
            property = "type"
    )
    @JsonSubTypes({
            @JsonSubTypes.Type(value = JobTitle.class, name = "jobTitle"),
            @JsonSubTypes.Type(value = IMG.class, name = "img")
    })
    public static abstract class Body{}
    public static class JobTitle extends Body{
        private String jobTitle;

        public String getJobTitle() {
            return jobTitle;
        }

        public void setJobTitle(String jobTitle) {
            this.jobTitle = jobTitle;
        }
    }
    public static class IMG extends Body{
        private String data;

        public String getData() {
            return data;
        }

        public void setData(String data) {
            this.data = data;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper om = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);;
        JobTitle jt = new JobTitle();
        jt.setJobTitle("job title");
        System.out.println(om.writeValueAsString(jt));
        IMG img = new IMG();
        img.setData("xxxxx");
        System.out.println(om.writeValueAsString(img));
        ArrayList<Response<?>> rs = new ArrayList<Response<?>>();
        Response<JobTitle> r1 = new Response<JobTitle>();
        r1.setId("1");
        r1.setBody(jt);
        rs.add(r1);
        Response<IMG> r2 = new Response<IMG>();
        r2.setId("2");
        r2.setBody(img);
        rs.add(r2);
        System.out.println(om.writeValueAsString(rs));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM