将HashMap.toString()转换回Java中的HashMap
我将一个键值对放在Java HashMap
并使用toString()
方法将其转换为String
。
是否可以将此String
表示forms转换回HashMap
对象并使用其对应的键检索该值?
谢谢
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()); }
将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()的说明
以下是序列化说明的示例代码。
并将hashMap作为arg传递给方法。
public void sayHello(Map m){ } //calling block Map hm = new HashMap(); sayHello(hm);
如果toString()包含恢复对象所需的所有数据,它将起作用。 例如,它适用于字符串映射(其中字符串用作键和值):
// create map Map map = new HashMap(); // 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 map2 = new HashMap(); for (Map.Entry
虽然我真的不明白为什么你需要这个,但这有效。
我使用toString()方法将HashMap转换为String并传递给另一个接受String的方法并将此String转换为HashMap对象
传递HashMap是一种非常非常糟糕的方法。
它理论上可以起作用,但是有太多可能出错的地方(并且它会表现得非常糟糕)。 显然,在你的情况下出现问题。 没有看到你的代码,我们不能说什么。
但更好的解决方案是更改“另一个方法”,以便它只将HashMap
作为参数而不是一个String表示forms。
你尝试了什么?
objectOutputStream.writeObject(hashMap);
应该工作得很好,只要hashMap中的所有对象都实现Serializable。
您无法从字符串恢复为对象。 所以你需要这样做:
HashMap map = new HashMap(); //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 newMap = oi.readObject(); oi.close();
你不能直接这样做,但我这样做是疯狂的,如下所示……
基本思路是,首先你需要将HashMap String转换为Json,然后你可以再次使用Gson / Genson等将Json反序列化为HashMap。
@SuppressWarnings("unchecked") private HashMap toHashMap(String s) { HashMap 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 map = new HashMap(); map.put("Name", "Suleman"); map.put("Country", "Pakistan"); String s = map.toString(); HashMap newMap = toHashMap(s); System.out.println(newMap);
你只能使用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(); }
可以从字符串表示中重建集合,但如果集合的元素不覆盖它们自己的toString
方法,则它将不起作用。
因此,使用像XStream这样的第三方库更加安全和容易,它可以在人类可读的XML中传输对象。
我希望你实际上需要通过传递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; }
这份工作适合我。
这可能是低效和间接的。 但
String mapString = "someMap.toString()"; new HashMap<>(net.sf.json.JSONObject.fromObject(mapString));
应该管用 !!!