简体   繁体   English

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

[英]Convert a string array to an object array

I have a String array contains name , age , and gender of 10 customers.我有一个String数组,其中包含 10 个客户的nameagegender I tried to convert it to Customer array.我试图将其转换为Customer数组。 I tried to copy each elements of String array into Customer array but it's not compatible.我试图将String数组的每个元素复制到Customer数组中,但它不兼容。 How do I insert elements from String array into Customer array?如何将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];
}

Assuming that Customer class has an all-args constructor Customer(String name, int age, String gender) and the input array contains all the fields like:假设Customer class 有一个all-args构造函数Customer(String name, int age, String gender)并且输入数组包含所有字段,如:

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

The array of customers may be created and populated like this:可以像这样创建和填充客户数组:

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]);
}

Create a temporary customer object inside the loop and populate it with the data.在循环内创建一个临时客户 object 并用数据填充它。 Then assign custs[x] to the temporary object.然后将 custs[x] 分配给临时 object。

If you have a 2d array of strings and an all-args constructor in the Customer class, then you can convert an array of strings to an array of objects like this:如果您在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: Output:

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

You have json string, use objectMapper to convert json string to object.您有 json 字符串,使用 objectMapper 将 json 字符串转换为 object。

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

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