解析映射中具有key = value对的字符串? [英] Parse a string with key=value pair in a map?

查看:206
本文介绍了解析映射中具有key = value对的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面有一个字符串,该字符串的格式为key1=value1, key2=value2,需要将其作为key=value加载到地图(Map<String, String>)中,因此我需要对逗号,进行分割,然后将cossn加载为键和0其值.

I have below String which is in the format of key1=value1, key2=value2 which I need to load it in a map (Map<String, String>) as key=value so I need to split on comma , and then load cossn as key and 0 its value.

String payload = "cossn=0, itwrqm=200006033213";
Map<String, String> holder =
          Splitter.on(",").trimResults().withKeyValueSeparator("=").split(payload);

我在这里使用Splitter为我完成这项工作,但在某些情况下失败了.对于我的某些字符串,value有一些带等号的字符串.因此,对于下面的字符串,它对我来说是失败的:

I am using Splitter here to do the job for me but for some cases it is failing. For some of my strings, value has some string with equal sign. So for below string it was failing for me:

String payload = "cossn=0, abc=hello/=world";

如何使其适用于上述情况?对于上述情况,key将为abc,值应为hello/=world.这可能吗?

How can I make it work for above case? For above case key will be abc and value should be hello/=world. Is this possible to do?

推荐答案

您可以添加一个数字来表示要拆分多少个拆分,只需添加2个即可拆分

you can add a number to say how many splits you want just add a 2 to split

import java.util.HashMap;

public class HelloWorld{

     public static void main(String []args){
        HashMap<String, String> holder = new HashMap();
        String payload = "cossn=0, abc=hello/=world";
        String[] keyVals = payload.split(", ");
        for(String keyVal:keyVals)
        {
          String[] parts = keyVal.split("=",2);
          holder.put(parts[0],parts[1]);
        }

     }
}

这篇关于解析映射中具有key = value对的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆