在 Java 中将 HashMap.toString() 转换回 HashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3957094/
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
Convert HashMap.toString() back to HashMap in Java
提问by Sameek Mishra
I put a key-value pair in a Java HashMap
and converted it to a String
using the toString()
method.
我将一个键值对放在 Java 中,HashMap
并String
使用该toString()
方法将其转换为 a 。
Is it possible to convert this String
representation back to a HashMap
object and retrieve the value with its corresponding key?
是否可以将此String
表示转换回HashMap
对象并使用其相应的键检索值?
Thanks
谢谢
采纳答案by Jigar Joshi
toString()
approach relies on implementation of toString()
and it can be lossy in most of the cases.
toString()
方法依赖于实现,toString()
并且在大多数情况下可能是有损的。
There cannot be non lossy solution here. but a better one would be to use Object serialization
这里不可能有非有损解决方案。但更好的方法是使用对象序列化
serialize Object to String
将对象序列化为字符串
private static String serialize(Serializable o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
deserialize String back to Object
将字符串反序列化回对象
private static Object deserialize(String s) throws IOException,
ClassNotFoundException {
byte[] data = Base64.getDecoder().decode(s);
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(data));
Object o = ois.readObject();
ois.close();
return o;
}
Here if the user object has fields which are transient, they will be lost in the process.
在这里,如果用户对象具有瞬态的字段,它们将在此过程中丢失。
old answer
旧答案
Once you convert HashMap to String using toString(); It's not that you can convert back it to Hashmap from that String, Its just its String representation.
使用 toString() 将 HashMap 转换为 String 后;并不是说您可以将它从该字符串转换回 Hashmap,它只是它的字符串表示。
You can either pass the reference to HashMap to method or you can serialize it
您可以将 HashMap 的引用传递给方法,也可以将其序列化
Here is the description for toString() toString()
Hereis the sample code with explanation for Serialization.
下面是 toString() toString()的描述
这里是带有序列化解释的示例代码。
and to pass hashMap to method as arg.
并将 hashMap 作为 arg 传递给方法。
public void sayHello(Map m){
}
//calling block
Map hm = new HashMap();
sayHello(hm);
回答by djna
What did you try?
你尝试了什么?
objectOutputStream.writeObject(hashMap);
should work just fine, providing that all the objects in the hashMap implement Serializable.
应该可以正常工作,前提是 hashMap 中的所有对象都实现了可序列化。
回答by Boris Pavlovi?
It is possible to rebuild a collection out of its string presentation but it will not work if the elements of the collection don't override their own toString
method.
可以从它的字符串表示中重建一个集合,但如果集合的元素没有覆盖它们自己的toString
方法,它将无法工作。
Therefore it's much safer and easier to use third party library like XStreamwhich streams objects in human readable XML.
因此,使用像XStream这样的第三方库更安全、更容易,它以人类可读的 XML 传输对象。
回答by zengr
You cannot revert back from string to an Object. So you will need to do this:
您无法从字符串恢复为对象。所以你需要这样做:
HashMap<K, V> map = new HashMap<K, V>();
//Write:
OutputStream os = new FileOutputStream(fileName.ser);
ObjectOutput oo = new ObjectOutputStream(os);
oo.writeObject(map);
oo.close();
//Read:
InputStream is = new FileInputStream(fileName.ser);
ObjectInput oi = new ObjectInputStream(is);
HashMap<K, V> newMap = oi.readObject();
oi.close();
回答by Michael Borgwardt
i converted HashMap into an String using toString() method and pass to the another method that take an String and convert this String into HashMap object
我使用 toString() 方法将 HashMap 转换为 String 并传递给采用 String 并将此 String 转换为 HashMap 对象的另一个方法
This is a very, very badway to pass around a HashMap.
这是传递 HashMap 的一种非常非常糟糕的方式。
It can theoretically work, but there's just way too much that can go wrong (and it will perform very badly). Obviously, in your case something does go wrong. We can't say what without seeing your code.
它理论上可以工作,但可能出错的地方太多了(而且性能会很差)。显然,在您的情况下,确实出现了问题。如果没有看到您的代码,我们无法说什么。
But a much better solution would be to change that "another method" so that it just takes a HashMap
as parameter rather than a String representation of one.
但是更好的解决方案是更改“另一种方法”,使其仅采用一个HashMap
作为参数而不是一个的字符串表示形式。
回答by AlexR
It will work if toString() contains all data needed to restore the object. For example it will work for map of strings (where string is used as key and value):
如果 toString() 包含恢复对象所需的所有数据,它将起作用。例如,它将适用于字符串映射(其中字符串用作键和值):
// create map
Map<String, String> map = new HashMap<String, String>();
// populate the map
// create string representation
String str = map.toString();
// use properties to restore the map
Properties props = new Properties();
props.load(new StringReader(str.substring(1, str.length() - 1).replace(", ", "\n")));
Map<String, String> map2 = new HashMap<String, String>();
for (Map.Entry<Object, Object> e : props.entrySet()) {
map2.put((String)e.getKey(), (String)e.getValue());
}
This works although I really do not understand why do you need this.
虽然我真的不明白你为什么需要这个,但这是有效的。
回答by Vinothkumar Arputharaj
Are you restricted to use only HashMap
??
你仅限于使用HashMap
吗??
Why can't it be so much flexible JSONObject
you can do a lot with it.
为什么它不能如此灵活,JSONObject
你可以用它做很多事情。
You can convert String jsonString
to JSONObject jsonObj
您可以转换String jsonString
为JSONObject jsonObj
JSONObject jsonObj = new JSONObject(jsonString);
Iterator it = jsonObj.keys();
while(it.hasNext())
{
String key = it.next().toString();
String value = jsonObj.get(key).toString();
}
回答by Muhammad Suleman
you cannot do this directly but i did this in a crazy way as below...
你不能直接做到这一点,但我以一种疯狂的方式做到了这一点,如下所示......
The basic idea is that, 1st you need to convert HashMap String into Json then you can deserialize Json using Gson/Genson etc into HashMap again.
基本思想是,首先您需要将 HashMap 字符串转换为 Json,然后您可以再次使用 Gson/Genson 等将 Json 反序列化为 HashMap。
@SuppressWarnings("unchecked")
private HashMap<String, Object> toHashMap(String s) {
HashMap<String, Object> map = null;
try {
map = new Genson().deserialize(toJson(s), HashMap.class);
} catch (TransformationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
private String toJson(String s) {
s = s.substring(0, s.length()).replace("{", "{\"");
s = s.substring(0, s.length()).replace("}", "\"}");
s = s.substring(0, s.length()).replace(", ", "\", \"");
s = s.substring(0, s.length()).replace("=", "\":\"");
s = s.substring(0, s.length()).replace("\"[", "[");
s = s.substring(0, s.length()).replace("]\"", "]");
s = s.substring(0, s.length()).replace("}\", \"{", "}, {");
return s;
}
implementation...
执行...
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("Name", "Suleman");
map.put("Country", "Pakistan");
String s = map.toString();
HashMap<String, Object> newMap = toHashMap(s);
System.out.println(newMap);
回答by Ayush Goyal
I hope you actually need to get the value from string by passing the hashmap key. If that is the case, then we don't have to convert it back to Hashmap. Use following method and you will be able to get the value as if it was retrieved from Hashmap itself.
我希望您实际上需要通过传递 hashmap 键来从字符串中获取值。如果是这种情况,那么我们不必将其转换回 Hashmap。使用以下方法,您将能够获得该值,就像它是从 Hashmap 本身检索到的一样。
String string = hash.toString();
String result = getValueFromStringOfHashMap(string, "my_key");
/**
* To get a value from string of hashmap by passing key that existed in Hashmap before converting to String.
* Sample string: {fld_category=Principal category, test=test 1, fld_categoryID=1}
*
* @param string
* @param key
* @return value
*/
public static String getValueFromStringOfHashMap(String string, String key) {
int start_index = string.indexOf(key) + key.length() + 1;
int end_index = string.indexOf(",", start_index);
if (end_index == -1) { // because last key value pair doesn't have trailing comma (,)
end_index = string.indexOf("}");
}
String value = string.substring(start_index, end_index);
return value;
}
Does the job for me.
为我做这份工作。
回答by Akash EJ
This may be inefficient and indirect. But
这可能是低效和间接的。但
String mapString = "someMap.toString()";
new HashMap<>(net.sf.json.JSONObject.fromObject(mapString));
should work !!!
应该管用 !!!