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

时间:2010-10-18 06:59:10

标签: java hashmap

我将一个键值对放在Java HashMap中,并使用String方法将其转换为toString()

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

由于

12 个答案:

答案 0 :(得分:20)

如果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());
}

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

答案 1 :(得分:10)

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

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

将对象序列化为字符串

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());
}

将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;
}

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


旧回答


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

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

以下是toString()toString()的说明 Here是示例代码,其中包含序列化的说明。

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

public void sayHello(Map m){

}
//calling block  
Map  hm = new HashMap();
sayHello(hm);

答案 2 :(得分:5)

  

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

这是一种传递HashMap的非常强大的非常糟糕的方式。

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

但更好的解决方案是更改“另一个方法”,以便它只需要HashMap作为参数而不是一个字符串表示。

答案 3 :(得分:4)

你不能直接这样做,但我是以疯狂的方式做到这一点,如下所示......

基本思想是,首先你需要将HashMap String转换为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;
}

...实施

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);

答案 4 :(得分:3)

你尝试了什么?

objectOutputStream.writeObject(hashMap);

应该可以正常工作,只要hashMap中的所有对象都实现Serializable。

答案 5 :(得分:3)

您无法从字符串恢复为对象。所以你需要这样做:

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();

答案 6 :(得分:3)

您是否仅限于使用HashMap ??

为什么它不能如此灵活JSONObject你可以用它做很多事情。

您可以将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();
}

答案 7 :(得分:0)

可以从字符串表示中重建集合,但如果集合的元素没有覆盖它们自己的toString方法,它将无法工作。

因此,使用像XStream这样的第三方库更安全,更容易,它可以用人类可读的XML来传输对象。

答案 8 :(得分:0)

我希望你真的需要通过传递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;
}

这份工作对我而言。

答案 9 :(得分:0)

使用ByteStream可以转换String,但是在大String的情况下,它可能会遇到OutOfMemory异常。 Baeldung在他的花盆中提供了一些不错的解决方案:https://www.baeldung.com/java-map-to-string-conversion

使用StringBuilder:

public String convertWithIteration(Map<Integer, ?> map) {
StringBuilder mapAsString = new StringBuilder("{");
for (Integer key : map.keySet()) {
    mapAsString.append(key + "=" + map.get(key) + ", ");
}
mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append("}");
return mapAsString.toString(); }

请注意,lambda仅适用于8级及以上的语言 使用流:

public String convertWithStream(Map<Integer, ?> map) {
String mapAsString = map.keySet().stream()
  .map(key -> key + "=" + map.get(key))
  .collect(Collectors.joining(", ", "{", "}"));
return mapAsString; }

使用Stream将字符串转换回Map:

public Map<String, String> convertWithStream(String mapAsString) {
Map<String, String> map = Arrays.stream(mapAsString.split(","))
  .map(entry -> entry.split("="))
  .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
return map; }

答案 10 :(得分:0)

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

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

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

yourMap = new Gson().fromJson(yourString, HashMap.class);

就这样享受。

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

答案 11 :(得分:-1)

这可能是低效和间接的。但

    String mapString = "someMap.toString()";
    new HashMap<>(net.sf.json.JSONObject.fromObject(mapString));

应该工作!!!