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

发布于 2024-09-27 13:26:35 字数 190 浏览 0 评论 0原文

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

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

谢谢

I put a key-value pair in a Java HashMap and converted it to a String using the toString() method.

Is it possible to convert this String representation back to a HashMap object and retrieve the value with its corresponding key?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

不奢求什么 2024-10-04 13:26:35

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

尽管我真的不明白为什么需要它,但它仍然有效。

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

// 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.

蓝色星空 2024-10-04 13:26:35

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

字符串反序列化回对象

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;这并不是说你可以将它从该字符串转换回 Hashmap,它只是它的字符串表示形式。

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

这是 toString() 的说明 toString()
这里是带有序列化说明的示例代码。

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

public void sayHello(Map m){

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

toString() approach relies on implementation of toString() and it can be lossy in most of the cases.

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.

You can either pass the reference to HashMap to method or you can serialize it

Here is the description for toString() toString()
Here is the sample code with explanation for Serialization.

and to pass hashMap to method as arg.

public void sayHello(Map m){

}
//calling block  
Map  hm = new HashMap();
sayHello(hm);
看轻我的陪伴 2024-10-04 13:26:35

你不能直接做到这一点,但我用一种疯狂的方式做到了如下...

基本思想是,首先你需要将 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);

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.

@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);
不如归去 2024-10-04 13:26:35

我将 HashMap 转换为字符串
使用 toString() 方法并传递给
另一种采用 String 的方法
并将这个String转换成HashMap
对象

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

理论上它可以工作,但是有太多可能出错的地方(而且它的性能会非常糟糕)。显然,在你的情况下确实出了问题。如果没有看到您的代码,我们就无法说出什么。

但更好的解决方案是更改“另一种方法”,以便它仅采用 HashMap 作为参数,而不是 HashMap 的字符串表示形式。

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

This is a very, very bad way to pass around a 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.

能否归途做我良人 2024-10-04 13:26:35

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

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

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

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

就是这样。

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

You can make use of Google's "GSON" open-source Java library for this,

Example input (Map.toString) : {name=Bane, id=20}

To Insert again in to HashMap you can use below code:

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

That's it.

(In Jackson Library mapper It will produce exception "expecting double-quote to start field name")

油焖大侠 2024-10-04 13:26:35

你尝试了什么?

objectOutputStream.writeObject(hashMap);

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

What did you try?

objectOutputStream.writeObject(hashMap);

should work just fine, providing that all the objects in the hashMap implement Serializable.

我一直都在从未离去 2024-10-04 13:26:35

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

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

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();
放血 2024-10-04 13:26:35

您是否被限制只能使用 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();
}

Are you restricted to use only HashMap ??

Why can't it be so much flexible JSONObject you can do a lot with it.

You can convert String jsonString to 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();
}
明月夜 2024-10-04 13:26:35

使用 ByteStream 可以转换 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 及以上可用
使用 Stream :使用

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

Stream 将字符串转换回映射:

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

Using ByteStream can convert the String but it can encounter OutOfMemory exception in case of large Strings. Baeldung provides some nice solutions in his pot here : https://www.baeldung.com/java-map-to-string-conversion

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

Please note that lambdas are only available at language level 8 and above
Using Stream :

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

Converting String Back to Map using Stream :

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; }
零時差 2024-10-04 13:26:35

我希望您实际上需要通过传递哈希图键来从字符串中获取值。如果是这种情况,那么我们就不必将其转换回 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;
}

为我做这份工作。

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.

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.

他夏了夏天 2024-10-04 13:26:35

可以从其字符串表示形式重建集合,但如果集合的元素不重写它们自己的 toString 方法,则它将不起作用。

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

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.

Therefore it's much safer and easier to use third party library like XStream which streams objects in human readable XML.

人间☆小暴躁 2024-10-04 13:26:35

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

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

应该有效!

This may be inefficient and indirect. But

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

should work !!!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文