java - 如何自动将 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
、、、clientPhone
等products
。我只需要将 Json Array 元素映射到 Order。
有一个支持反射的库(Jackson)并给了我一种相反的方法:Order to Json,但我找不到一种方法来做我想做的事。
解决方案
使用 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 示例
推荐阅读
- c# - 将 XML 文件加载到 ReaderSetting
- react-native - 使用开玩笑超时错误进行排毒:“分配给未定义”
- ios - ios swift 5 5分钟后定时器完成时如何删除单元格索引,当调用api时不会重复相同索引的定时器
- javascript - 如果我在 javascript 的单个脚本标记内调用 2 个函数会发生什么?
- javascript - 在 html 或 javascript 中使用 Li 更改 Div
- node.js - 如何增加发出https请求的nodejs自定义库的tps(吞吐量)
- javascript - jquery toggle between ID's based on element attribute
- html - 当一个 html 元素被翻译然后旋转时,它会沿对角线移动
- botframework - 如何在 Teams 自适应卡的 ChoiceSet 中换行?
- java - Spring 单元测试:我应该为 REST 控制器注入服务吗?