将String转换为ArrayList <myclass> </myclass>

时间:2014-07-28 14:58:15

标签: java collections

我想像这样转换String myString

[ ["cd",5,6,7], ["rtt",55,33,12], ["by65",87,87,12] ]

加入ArrayList<CustomClass>

CustomClass有构造函数的地方:

public CustomClass (String name, int num1, int num2, int num3)

我首先尝试创建ArrayList的{​​{1}}:

Strings

没为我工作......

我怎样才能得到类似的东西:

List<String> List = new ArrayList<String>(Arrays.asList(myString.split("[")));

首先List - {CustomClass,CustomClass,CustomClass,CustomClass}

CustomClass = CustomClass.name="cd" , CustomClass.num1=5,CustomClass.num2=7...

依旧......

2 个答案:

答案 0 :(得分:1)

你可以做点什么。如果你不能保证字符串格式,那么你可能需要为拼接数组长度和索引添加额外的检查。

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class CustomClass {
    String name;
    int num1;
    int num2;
    int num3;

    public CustomClass(String name, int num1, int num2, int num3) {
        super();
        this.name = name;
        this.num1 = num1;
        this.num2 = num2;
        this.num3 = num3;
    }
}

public class Sample {

    public static void main(String[] args) {
        String str = "[ [\"cd\",5,6,7], [\"rtt\",55,33,12], [\"by65\",87,87,12] ]";
        Pattern p = Pattern.compile("\\[(.*?)\\]");
        Matcher m = p.matcher(str.substring(1));
        List<CustomClass> customList = new ArrayList<CustomClass>();
        while (m.find()) {
            String[] arguments = m.group(1).split(",");
            customList.add(new CustomClass(arguments[0], 
                                            Integer.parseInt(arguments[1]), 
                                            Integer.parseInt(arguments[2]), 
                                            Integer.parseInt(arguments[3])));
        }
    }

}

Gson解决方案

public static void main(String[] args) {
    String json = "[ [\"cd\",5,6,7], [\"rtt\",55,33,12], [\"by65\",87,87,12] ]";
    List<CustomClass> customList = new ArrayList<CustomClass>();
    String[][] data = new Gson().fromJson(json, String[][].class);
    for (String[] strArray : data){
        customList.add(new CustomClass(strArray[0], 
                Integer.parseInt(strArray[1]), 
                Integer.parseInt(strArray[2]), 
                Integer.parseInt(strArray[3])));
    }
    System.out.println(customList);
}

答案 1 :(得分:0)

这是一个快速的“手动”解析器。

public static List<CustomClass> parseString(String str) {
    String [] elements = str.split("\\[");
    List <CustomClass> result = new ArrayList<CustomClass>();

    for (String elem : elements) {
        if (elem.contains("]")) {
            String seq = elem.substring(0, elem.indexOf(']'));
            String [] tokens = seq.split(",");
            result.add(new CustomClass(tokens[0].substring(1,tokens[0].length()-1),
                    Integer.parseInt(tokens[1]), 
                    Integer.parseInt(tokens[2]),
                    Integer.parseInt(tokens[3])));
        }
    }

    return result;
}

请注意我依靠保证正确的输入。你可能想根据需要调整这个。