java - 请问包含多项键值对的字符串怎么转成 List<Map<string,String>?
迷茫
迷茫 2017-04-18 10:54:35
0
3
701

如 String:“{refer=1, servic=info}, {refer=2, service=client}, {refer=3, service=client}”

怎么才能转成 List<Map<string,String> 呢?
也不能 split(",") 因为字符串中 map 里也有逗号。希望得到大家的帮助!感谢!

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
左手右手慢动作

I originally thought it was in the form of json object + comma, but I didn’t expect it was not even json. Use regular expressions, or write a parser.

{([a-zA-Z0-9_-,=.])}

Repeat split(',') to get your kv pair

左手右手慢动作

It’s true that it can’t be done directly split(","),但是为什么不 split("},")?

小葫芦

This string looks like JSON, so just turn it into JSON and then convert it into the type you want.
The specific implementation is as follows:

// 你的字符串
String str = "{refer=1, servic=info},{refer=2, service=client}, {refer=3,service=client}";
// 变成JSONArray的样子
str = "[" + str + "]" ;

// 使用Gson转换成你想要的样子
Gson gson = new Gson();
List<Map<String,String>> list = gson.fromJson(str, new TypeToken<List<Map<String, String>>>() {}.getType());

// 打印一下
list.forEach(System.out::println);

Tested and correct.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template