在Java中将HashMap.toString()转换回HashMap

Sam*_*hra 29 java hashmap

我在Java中放了一个键值对,HashMapString使用该toString()方法将其转换为a .

是否可以将此String表示转换回HashMap对象并使用其对应的键检索值?

谢谢

Ale*_*exR 21

如果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());
}
Run Code Online (Sandbox Code Playgroud)

这有效,虽然我真的不明白为什么你需要这个.


Jig*_*shi 11

toString()方法依赖于实施,toString()在大多数情况下它可能是有损的.

这里不能有无损解决方案.但更好的方法是使用对象序列化

将对象序列化为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());
}
Run Code Online (Sandbox Code Playgroud)

将String反序列化回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;
}
Run Code Online (Sandbox Code Playgroud)

如果用户对象具有瞬态字段,则它们将在此过程中丢失.


老答案


使用toString()将HashMap转换为String后; 这不是你可以从那个String转换回Hashmap,它只是它的String表示.

您可以将对HashMap的引用传递给方法,也可以将其序列化

以下是toString()toString()的描述
以下是序列化解释的示例代码.

并将hashMap作为arg传递给方法.

public void sayHello(Map m){

}
//calling block  
Map  hm = new HashMap();
sayHello(hm);
Run Code Online (Sandbox Code Playgroud)


Muh*_*man 6

您不能直接执行此操作,但是我以如下疯狂的方式执行了此操作...

基本思想是,首先需要将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;
}
Run Code Online (Sandbox Code Playgroud)

实施...

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);
Run Code Online (Sandbox Code Playgroud)


Mic*_*rdt 5

我使用toString()方法将HashMap转换为String并传递给另一个采用String并将此String转换为HashMap对象的方法

传递HashMap 是一种非常非常糟糕的方法.

理论上它可以起作用,但是可能出错的方式太多了(它会表现得非常糟糕).显然,在你的情况下出现问题.如果没有看到您的代码,我们无法说出什么.

但更好的解决方案是更改"另一个方法",以便它只需要一个HashMapas参数而不是一个String表示.

  • 我认为他的意思是在不同的实例中调用这些方法.即实例A将`Map`序列化为字符串,实例B必须将字符串反序列化为`Map`对象. (2认同)

Gop*_*sgn 5

为此,您可以使用 Google 的“GSON”开源 Java 库,

输入示例 (Map.toString):{name=Bane, id=20}

要再次插入到 HashMap 中,您可以使用以下代码:

yourMap = new Gson().fromJson(yourString, HashMap.class);
Run Code Online (Sandbox Code Playgroud)

就是这样。

(在杰克逊图书馆映射器中它将产生异常“期望双引号开始字段名称”)