简体   繁体   English

用杰克逊反序列化嵌套的json对象

[英]Deserializing nested json object with Jackson

I would like to ask you guys how to deserialize nested object with jackson. 我想问你们如何用杰克逊反序列化嵌套对象。 I got example Json File: 我有示例Json File:

{
    "id": "1",              
    "comment": "Some comment",
    "user": "Smith",
    "date": "2018-05-31",
    "shape": "oval",
    "coordinates": [ ["50", "130"], ["370", "500"] ]
}, 

Let's say that main Class is called Comment , but I would like to create another class Coordinates with local variables x1, x2, y1, y2 . 比方说,主类是所谓的Comment ,但我想创建另一个类Coordinates与局部变量x1, x2, y1, y2 So class Comment looks like that: 所以类Comment看起来像这样:

 public class CommentFile implements Serializable{
    private Long id;
    private String comment;
    private String user;
    private String date;
    private String shape;
    private Coordinates coordinates;
    //setters, getters, constructor

But because in json i have 'array' "coordinates": [ ["50", "130"], ["370", "500"] ] , i dont know how to convert this to: 但是因为在json中我有'array' "coordinates": [ ["50", "130"], ["370", "500"] ] ,所以我不知道如何将其转换为:

public class Coordinates implements Serializable{
private double x1;
private double y1;
private double x2;
private double y2;

Any ideas? 有任何想法吗?

A straightforward way is to use List<List<String>> coordinates; 一种简单的方法是使用List<List<String>> coordinates; to deserialize the JSON to Java first. 首先将JSON反序列化为Java。 Later, you can implement a method something like getCoordinatesObject() inside CommentFile class to create and get a Coordinates object. 稍后,您可以在CommentFile类中实现类似于getCoordinatesObject()的方法来创建和获取Coordinates对象。

There might be a better way to accomplish this directly with Jackson but you can do this as well. 也许有更好的方法直接与Jackson一起完成此操作,但是您也可以这样做。

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

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