【问题标题】:Best way to handle child data(array) in REST API在 REST API 中处理子数据(数组)的最佳方式
【发布时间】:2015-10-21 11:13:07
【问题描述】:

我正在开发网络 API。 (使用java,jersey)(数据格式json)

以下是示例数据格式。

customerID
customerName
customerCity
products
    product1  quantity1
    product2  quantity2
    product3  quantity3

正如您在上面的数据中看到的,产品是一个数组(产品和数量)。

为了提供这些数据(json 格式),我使用了 POJO:

public class CustomerOrder
{
    private String customerID;
    private String customerName;
    private String customerCity;
    private ArrayList<Product> products;

    //getters & setters for above 4 variables

    public CustomerOrder() {}  //Constructor without parameter

    public CustomerOrder(....) {....}  //Constructor with above 4 parameter

    public class Product
    {
        private String product;
        private int quantity;

        //getters & setters for above 2 variables
    }
}

使用上面的 POJO:

ArrayList<CustomerOrder> customerOrderList = new ArrayList<CustomerOrder>();

ArrayList<Product> customerOrderProductList = new ArrayList<Product>();
//statements to add data in customerOrderProductList

//add data in customerOrderList
customerOrderList.add(
    customerID,
    customerName, 
    customerCity,
    customerOrderProductList
);

我的问题是,这是处理上述数据格式的最佳(标准)方法吗?或者有没有更好的方法?

【问题讨论】:

标签: java json rest jersey


【解决方案1】:

是的,这是处理数据格式的标准方法。如果你真的想的话,你可以用 Product 的数组来切换列表,但这真的没有必要。

除此之外,大多数 json 到 POJO 库(gson 等)不需要 getter 和 setter - 您只需将变量声明为 public。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2021-12-30
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 2013-01-27
    相关资源
    最近更新 更多