将字符串解析为键值对象

时间:2013-06-01 17:36:23

标签: java arrays string

我有以下字符串列表

[customer=dan, Date=Wed Sep 16 06:42:18  1938,company=abbc] 
[customer=ben, Date=Sun May 19 13:12:51  1956,company=tss] 

我想从它的列表列表构建。 例如

<customer,dan>
<Date,Wed Sep 16 06:42:18  1938>
<company,abbc>

我应该如何解析这个字符串?

1 个答案:

答案 0 :(得分:1)

您可以使用split方法解析输入字符串(假设公司和客户名称不包含任何逗号或]字符。这样的内容应该有效:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

class Element {

    String customer;
    Date date;
    String company;
    static SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");

    void setDate(String date) {
        try {
            this.date = sdf.parse(date);
        } catch (ParseException ex) {
            // Do something if parsing fails
        }
    }

    @Override
    public String toString() {
        return "<customer," + customer + ">\n"
                + "<Date," + sdf.format(date) + ">\n"
                + "<company," + company + ">";
    }
}

public class ParseList {

    public static void main(String args[]) {
        List<String> list = new ArrayList<>();

        list.add("[customer=dan, Date=Wed Sep 16 06:42:18  1938,company=abbc]");
        list.add("[customer=ben, Date=Sun May 19 13:12:51  1956,company=tss]");

        List<Element> elementList = new ArrayList<>();
        for (String str : list) {
            String[] arr = str.split("[,\\]]"); // Split the string
            Element element = new Element();
            element.customer = arr[0].split("=")[1]; // Split again on the equals
            element.setDate(arr[1].split("=")[1]);
            element.company = arr[2].split("=")[1];
            elementList.add(element);
        }

        for (Element element : elementList) {
            System.out.println(element);
        }

    }
}