java中如何将String转换为Hashmap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26485964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert String into Hashmap in java
提问by Naresh kumar
How can I convert a String
into a HashMap
?
如何将 a 转换String
为 a HashMap
?
String value = "{first_name = naresh, last_name = kumar, gender = male}"
into
进入
Map<Object, Object> = {
first_name = naresh,
last_name = kumar,
gender = male
}
Where the keys are first_name
, last_name
and gender
and the values are naresh
, kumar
, male
.
其中键是first_name
,last_name
和gender
值是naresh
, kumar
, male
。
Note:Keys can be any thing like city = hyderabad
.
注意:键可以是任何类似city = hyderabad
.
I am looking for a generic approach.
我正在寻找一种通用的方法。
采纳答案by kai
This is one solution. If you want to make it more generic, you can us StringUtils
library.
这是一种解决方案。如果你想让它更通用,你可以使用我们的StringUtils
库。
String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1); //remove curly brackets
String[] keyValuePairs = value.split(","); //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();
for(String pair : keyValuePairs) //iterate over the pairs
{
String[] entry = pair.split("="); //split the pairs to get key and value
map.put(entry[0].trim(), entry[1].trim()); //add them to the hashmap and trim whitespaces
}
For example you can switch
例如你可以切换
value = value.substring(1, value.length()-1);
to
到
value = StringUtils.substringBetween(value, "{", "}");
if you are using StringUtils
which is contained in apache.commons.lang
package.
如果您正在使用包中StringUtils
包含的内容apache.commons.lang
。
回答by Ruchira Gayan Ranaweera
String value = "{first_name = naresh,last_name = kumar,gender = male}"
Let's start
开始吧
- Remove
{
and}
from theString
>>first_name = naresh,last_name = kumar,gender = male - Split the
String
from,
>> array of 3 element - Now you have an
array
with3
element - Iterate the
array
and split each element by=
- Create a
Map<String,String>
put each part separated by=
. first part asKey
and second part asValue
- 从>>first_name = naresh,last_name = kumar,gender = male 中删除
{
and}
String
- 拆分
String
from,
>> 3 个元素的数组 - 现在你有一个
array
with3
元素 - 迭代
array
并拆分每个元素=
- 创建一个
Map<String,String>
put 每个部分由=
. 第一部分作为Key
和第二部分作为Value
回答by Hiren
@Test
public void testToStringToMap() {
Map<String,String> expected = new HashMap<>();
expected.put("first_name", "naresh");
expected.put("last_name", "kumar");
expected.put("gender", "male");
String mapString = expected.toString();
Map<String, String> actual = Arrays.stream(mapString.replace("{", "").replace("}", "").split(","))
.map(arrayData-> arrayData.split("="))
.collect(Collectors.toMap(d-> ((String)d[0]).trim(), d-> (String)d[1]));
expected.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())));
}
回答by suliman alobody
try this out :)
试试这个:)
public static HashMap HashMapFrom(String s){
HashMap base = new HashMap(); //result
int dismiss = 0; //dismiss tracker
StringBuilder tmpVal = new StringBuilder(); //each val holder
StringBuilder tmpKey = new StringBuilder(); //each key holder
for (String next:s.split("")){ //each of vale
if(dismiss==0){ //if not writing value
if (next.equals("=")) //start writing value
dismiss=1; //update tracker
else
tmpKey.append(next); //writing key
} else {
if (next.equals("{")) //if it's value so need to dismiss
dismiss++;
else if (next.equals("}")) //value closed so need to focus
dismiss--;
else if (next.equals(",") //declaration ends
&& dismiss==1) {
//by the way you have to create something to correct the type
Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
base.put(tmpKey.toString(),ObjVal);//declaring
tmpKey = new StringBuilder();
tmpVal = new StringBuilder();
dismiss--;
continue; //next :)
}
tmpVal.append(next); //writing value
}
}
Object objVal = object.valueOf(tmpVal.toString()); //same as here
base.put(tmpKey.toString(), objVal); //leftovers
return base;
}
examples input : "a=0,b={a=1},c={ew={qw=2}},0=a" output : {0=a,a=0,b={a=1},c={ew={qw=2}}}
示例输入:“a=0,b={a=1},c={ew={qw=2}},0=a”输出:{0=a,a=0,b={a=1} ,c={ew={qw=2}}}
回答by tryingToLearn
Since I use Gsonquite liberally, I can share a Gson based approach:
由于我非常自由地使用Gson,我可以分享一个基于 Gson 的方法:
Map<Object,Object> attributes = gson.fromJson(gson.toJson(value)),Map.class);
What it does is:
它的作用是:
gson.toJson(value)
will serialize your object into its equivalent Json representation.gson.fromJson
will convert the Json string to specified object. (in this example -Map
)
gson.toJson(value)
将您的对象序列化为其等效的 Json 表示形式。gson.fromJson
将 Json 字符串转换为指定的对象。(在这个例子中 -Map
)
The flexibility with this approach is that you can pass an Object instead of String to toJson
method.
这种方法的灵活性在于您可以将对象而不是字符串传递给 toJson
方法。