简体   繁体   English

如何将多个列表分配给对象的属性?

[英]How can I assign multiple lists to a property of my object?

I have a product object that has a number of properties like this 我有一个产品对象,它具有许多这样的属性

public class Product {
     private int deal_id;
     private String deal_key;
     private String deal_title;
     private String url_title;
     private int deal_value;
.........//setters and getters
}

Every product has a number of sizes that can also be 0. I want to assign sizes to my product from values in the json data I receive(below). 每个产品的大小都可以为0。我想从我接收到的json数据(如下)中的值中为产品分配大小。 I am extending this class and now I need to add another property of size which is an array of arrays. 我正在扩展此类,现在我需要添加另一个size属性,即数组数组。 I need to set it from json on the api that like this. 我需要像这样从api上的json设置它。

"size" : [ { "product_size_id": "695", "deal_id": "179", "size_name": "None", "quantity": "1", "size_id": "1" }, 
           { "product_size_id": "695", "deal_id": "179", "size_name": "None", "quantity": "1", "size_id": "1" } ]

How can I set this on my product object in JAVA. 如何在JAVA中的产品对象上进行设置。 I have tried looking up Hashmaps and Arraylist but havent found a way to do it correctly. 我尝试查找Hashmaps和Arraylist,但还没有找到正确执行此操作的方法。

You can create an object for Size with all your properties 您可以使用所有属性为Size创建一个对象

public class Size {
    private int product_size_id;
    private int deal_id;
    private String size_name;
    private int quantity;
    private int size_id;
....setters and getters
}

Then you can set size as object and add it to Product as a List 然后,您可以将尺寸设置为对象并将其作为列表添加到产品中

private ArrayList<Size> yoursizes;

Two things that may help to find a solution to your problem. 有两件事可以帮助您找到问题的解决方案。

First you may want to parse the JSON input. 首先,您可能想解析JSON输入。 This answer may help you to get this done. 这个答案可以帮助您完成此任务。

Second I think you need a data structure that allows to assign multiple lists to a value (or something similar). 其次,我认为您需要一个允许将多个列表分配给一个值(或类似值)的数据结构。 There are libraries for Java to help you do this. 有Java库可以帮助您完成此任务。 Guava or Commons Collections are two examples. GuavaCommons Collections是两个示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM