我想问一下你们如何用jackson反序列化嵌套对象。 我得到了示例 Json 文件:
{
"id": "1",
"comment": "Some comment",
"user": "Smith",
"date": "2018-05-31",
"shape": "oval",
"coordinates": [ ["50", "130"], ["370", "500"] ]
},
假设主类名为 Comment
,但我想创建另一个类 Coordinates
带有局部变量x1, x2, y1, y2
。
所以类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
但是因为在 json 中我有“数组”"coordinates": [ ["50", "130"], ["370", "500"] ]
,我不知道如何将其转换为:
public class Coordinates implements Serializable{
private double x1;
private double y1;
private double x2;
private double y2;
有什么想法吗?
最佳答案
一个简单的方法是使用 List<List<String>> coordinates;
首先将 JSON 反序列化为 Java。稍后,您可以实现类似 getCoordinatesObject()
的方法里面CommentFile
类来创建并获取坐标对象。
可能有更好的方法可以直接与 Jackson 一起完成此任务,但您也可以这样做。
关于java - 使用 Jackson 反序列化嵌套 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50614532/