0

字符串格式是(不是json格式):</p>

a="0PN5J17HBGZHT7JJ3X82", b="frJIUN8DYpKDtOLCwo/yzg="

我想将此字符串转换为 HashMap:

a有价值的钥匙0PN5J17HBGZHT7JJ3X82

b有价值的钥匙frJIUN8DYpKDtOLCwo/yzg=

有没有方便的方法?谢谢

我试过的:

    Map<String, String> map = new HashMap<String, String>();
    String s = "a=\"00PN5J17HBGZHT7JJ3X82\",b=\"frJIUN8DYpKDtOLCwo/yzg=\"";
    String []tmp = StringUtils.split(s,',');
    for (String v : tmp) {
        String[] t = StringUtils.split(v,'=');
        map.put(t[0], t[1]);
    }   

我得到这个结果:

a有价值的钥匙"0PN5J17HBGZHT7JJ3X82"

b有价值的钥匙"frJIUN8DYpKDtOLCwo/yzg

对于 key a,开始和结束双引号 (") 是不需要的;对于 key b,开始双引号 (") 是不需要的,并且缺少最后一个等号 (=)。对不起我糟糕的英语。

4

4 回答 4

7

可能你不关心它是一个 HashMap,只是一个 Map,所以这会做到,因为 Properties 实现了 Map:

import java.io.StringReader;
import java.util.*;

public class Strings {
    public static void main(String[] args) throws Exception {
        String input = "a=\"0PN5J17HBGZHT7JJ3X82\", b=\"frJIUN8DYpKDtOLCwo/yzg=\"";
        String propertiesFormat = input.replaceAll(",", "\n");
        Properties properties = new Properties();
        properties.load(new StringReader(propertiesFormat));
        System.out.println(properties);
    }
}

输出:

{b="frJIUN8DYpKDtOLCwo/yzg=", a="0PN5J17HBGZHT7JJ3X82"}

如果您绝对需要一个 HashMap,您可以使用 Properties 对象作为输入构造一个:new HashMap(properties)

于 2012-12-31T04:49:52.670 回答
1

在的基础上拆分字符串,commas (",")然后使用 with("=")

String s = "Comma Separated String";
HashMap<String, String> map = new HashMap<String, String>();

String[] arr = s.split(",");

String[] arStr = arr.split("=");

map.put(arr[0], arr[1]);
于 2012-12-31T05:28:36.740 回答
1

在 Ryan 的代码中添加了一些更改

 public static void main(String[] args) throws Exception {
        String input = "a=\"0PN5J17HBGZHT7JJ3X82\", b=\"frJIUN8DYpKDtOLCwo/yzg=\"";
        input=input.replaceAll("\"", "");
        String propertiesFormat = input.replaceAll(",", "\n");
        Properties properties = new Properties();
        properties.load(new StringReader(propertiesFormat));
        Set<Entry<Object, Object>> entrySet = properties.entrySet();
        HashMap<String,String > map = new HashMap<String, String>();
        for (Iterator<Entry<Object, Object>> it = entrySet.iterator(); it.hasNext();) {
            Entry<Object,Object> entry = it.next();
            map.put((String)entry.getKey(), (String)entry.getValue());
        }
        System.out.println(map);
    }
于 2012-12-31T05:29:59.423 回答
0

您也可以使用下面的正则表达式。

Map<String,String> data = new HashMap<String,String>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
for ( int i=0; i+2 <= split.length; i+=2 ){
    data.put( split[i], split[i+1] );
}
return data;
于 2014-09-15T23:52:18.897 回答