繁体   English   中英

将字符串数组转换为 object 数组

[英]Convert a string array to an object array

我有一个String数组,其中包含 10 个客户的nameagegender 我试图将其转换为Customer数组。 我试图将String数组的每个元素复制到Customer数组中,但它不兼容。 如何将String数组中的元素插入到Customer数组中?

//String[] customerData is given but too long to copy
Customer[] custs = new Customer[numberOfCustomer];
for (int x = 0; x < customerData.length; x++) {
    custs[x] = customerData[x];
}

假设Customer class 有一个all-args构造函数Customer(String name, int age, String gender)并且输入数组包含所有字段,如:

String[] data = {
    "Name1", "25", "Male",
    "Name2", "33", "Female",
// ...
};

可以像这样创建和填充客户数组:

Customer[] customers = new Customer[data.length / 3];
for (int i = 0, j = 0; i < customers.length && j < data.length; i++, j += 3) {
    customers[i] = new Customer(data[j], Integer.parseInt(data[j + 1]), data[j + 2]);
}

在循环内创建一个临时客户 object 并用数据填充它。 然后将 custs[x] 分配给临时 object。

如果您在Customer class 中有一个二维字符串数组和一个全参数构造函数,那么您可以将字符串数组转换为对象数组,如下所示:

static class Customer {
    String name, age, gender;

    public Customer(String name, String age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    @Override
    public String toString() {
        return name + " " + age + " " + gender;
    }
}
public static void main(String[] args) {
    String[][] arrStr = {
            {"John1", "22", "Male"},
            {"John2", "21", "Male"},
            {"John3", "23", "Male"},
            {"John4", "24", "Male"},
            {"John5", "20", "Male"}};

    Customer[] customers = Arrays.stream(arrStr)
            // convert an array of strings to an array of objects
            .map(arr -> new Customer(arr[0], arr[1], arr[2]))
            .toArray(Customer[]::new);

    // output
    Arrays.stream(customers).forEach(System.out::println);
}

Output:

John1 22 Male
John2 21 Male
John3 23 Male
John4 24 Male
John5 20 Male

您有 json 字符串,使用 objectMapper 将 json 字符串转换为 object。

暂无
暂无

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

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