首页 > 解决方案 > 如何自动将 json 文档序列化为 java 对象(使用反射)

问题描述

我在 nodejs 上有一个简单的 API,用于存储 MongoDB 文档。我有一个 API 端点,可以检索 json 数组中的文档。

我想用 Java 为这个 API 实现一个客户端。由于 Java 支持反射,因此我不需要将数组中的每个 json 文档映射到具有相同字段的 java 对象中。必须有一种方法可以简单地将一个映射到另一个。但是,它必须支持嵌套对象。这是我在 Java 中的对象:

public class Order {
    public Boolean deleted;
    //Use only when updating an order, _id is mongo's _id of order to be updated
    public String _id;
    static public class Product {
        public String name;
        public Integer quantity;
        public Float price;
    }
    public String clientName;
    public String clientPhone;
    public Integer seller_id;
    public Integer order_id;
    public String observations;
    public ArrayList<Product> products = new ArrayList<Product>();
    public Float total;
}

我从 API 收到的 Json Array 将具有相同的成员:clientName、、、clientPhoneproducts。我只需要将 Json Array 元素映射到 Order。

有一个支持反射的库(Jackson)并给了我一种相反的方法:Order to Json,但我找不到一种方法来做我想做的事。

标签: javajsonapijackson

解决方案


使用 Jackson,您可以通过以下方式将 json 转换为 java 对象。

//json variable is the String represenating the json you have received from API
Order order = new ObjectMapper().readValue(json, Order.class);

有关更多示例,您可以查看Jackson 示例


推荐阅读