java - 使用 Jackson 反序列化嵌套 json 对象

标签 java json jackson

我想问一下你们如何用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/

相关文章:

java - 在Spring MVC中获取Windows用户名

java - 如何修复闪烁

javascript - 在 R 中将 rpart 输出转换为 JSON 格式

java - 如何解决使用InputStream存储资源路径的空指针异常?

java - 为什么会出现 "Exception in thread "AWT-EventQueue- 0"java.lang.OutOfMemoryError: Java heap space"错误?

java - Selenium 中的 headless Chrome 检索空页面(尽管没有 headless 标志也可以工作)

javascript - d3.min.js :1 Uncaught TypeError: n. getFullYear 不是函数

json - 在 Perl 中访问嵌套的 JSON 元素

java - 如何避免 Spring Boot 使用我的 MappingJackson2HttpMessageConverter Bean?

java - 为什么 Jackson 中的 JsonGeneratorDelegate 没有实现 setPrettyPrinter() ?