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

キーaの場合、開始と終了の二重引用符( ")は不要です。キー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オブジェクトを入力として使用してHashMapを作成できますnew HashMap(properties)

于 2012-12-31T04:49:52.670 に答える
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 に答える
1

に基づいて文字列を分割し、commas (",")次に("=")

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 に答える
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 に答える