用杰克逊对复杂的Json进行反序列化

时间:2014-04-23 13:56:15

标签: java json jackson

我遇到了一个"复杂的问题"杰森:

{
  "Books": [
    {
      "title": "Java",
      "instructions": [],
      "links": {
        "EJB": {
          "href": "www.java.com/EJB"
        }
      }
    },
    {
      "title": "C#",
      "instructions": [],
      "links": {
        "SOAP": {
          "href": "www.C#.com/SOAP"
        }
      }
    }]
}

有人可以告诉我如何反序列化这种JSON以获得POJO列表吗?

POJO必须是" Book"有3个字段:标题,说明和链接

谢谢。

2 个答案:

答案 0 :(得分:1)

您的初学者JSON存在根本问题;你有重复的成员名称。

在这种情况下,解析器的行为是未定义RFC 7159, section 4)。由于jsonschema2pojo使用Jackson,这意味着您将获得每个重复成员的 last 定义值。

使用数组:

[
{
  "title":"Title 1",
  "instructions" : [],
  "links": {
    "link 1": {
      "href": "The link 1"
    }
  }
},
{
   "title":"Title 2",
   "instructions" : [],
   "links": {
    "link 2": {
      "href": "The link 2"
    }
  }
}
]

然后,jsonschema2pojo不会真正反序列化为POJO;你真正想要的是为数组元素(即一个对象)定义类MyClass并使用Jackson的ObjectMapper来反序列化:

final TypeReference<List<MyClass>> typeref
    = new TypeReference<List<MyClass>>() {};

final ObjectMapper mapper = new ObjectMapper();

final List<MyClass> list = mapper.readValue(whatever, typeref);

答案 1 :(得分:0)

您的POJO课程可能如下所示:

class Books {

    @JsonProperty("Books")
    private List<Book> books;

    public List<Book> getBooks() {
        return books;
    }

    public void setBooks(List<Book> books) {
        this.books = books;
    }

    @Override
    public String toString() {
        return "Books [books=" + books + "]";
    }
}

class Book {

    private String title;
    private List<String> instructions;
    private Map<String, Link> links;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<String> getInstructions() {
        return instructions;
    }

    public void setInstructions(List<String> instructions) {
        this.instructions = instructions;
    }

    public Map<String, Link> getLinks() {
        return links;
    }

    public void setLinks(Map<String, Link> links) {
        this.links = links;
    }

    @Override
    public String toString() {
        return "Book [title=" + title + ", instructions=" + instructions + ", links=" + links + "]";
    }
}

class Link {

    private String href;

    public String getHref() {
        return href;
    }

    public void setHref(String href) {
        this.href = href;
    }

    @Override
    public String toString() {
        return href;
    }
}

简单用法:

ObjectMapper mapper = new ObjectMapper();

System.out.println(mapper.readValue(json, Books.class));

以上程序打印:

Books [books=[Book [title=Java, instructions=[], links={EJB=www.java.com/EJB}], Book [title=C#, instructions=[], links={SOAP=www.C#.com/SOAP}]]]