Home  >  Q&A  >  body text

java - 请问包含多项键值对的字符串怎么转成 List<Map<string,String>?

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

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

迷茫迷茫2743 days ago632

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 10:56:35

    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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:56:35

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

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 10:56:35

    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.

    reply
    0
  • Cancelreply