Convertir HashMap.toString () volver a HashMap en Java


Puse un par clave-valor en un Java HashMap y lo convertí en un String usando el método toString().

¿Es posible convertir esta representación String en un objeto HashMap y recuperar el valor con su clave correspondiente?

Gracias

Author: DontDivideByZero, 2010-10-18

10 answers

toString() enfoque se basa en la implementación de toString() y puede ser con pérdida en la mayoría de los casos.

No puede haber una solución sin pérdidas aquí. pero una mejor sería usar serialización de objetos

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

Deserializar Cadena de vuelta al objeto

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

Aquí si el objeto user tiene campos que son transitorios, se perderán en el proceso.


Antigua respuesta


Una vez que convierta HashMap a cadena usando toString (); No es que puedas convertirlo de vuelta a Hashmap desde esa Cadena, es solo su representación de Cadena.

Puede pasar la referencia al método HashMap to o puede serializarlo

Aquí está la descripción para toString() toString()
Aquí es el código de ejemplo con explicación para la Serialización.

Y pasar HashMap al método como arg.

public void sayHello(Map m){

}
//calling block  
Map  hm = new HashMap();
sayHello(hm);
 8
Author: Jigar Joshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-28 18:16:02

Funcionará si toString() contiene todos los datos necesarios para restaurar el objeto. Por ejemplo, funcionará para map of strings (donde string se usa como clave y valor):

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

Esto funciona aunque realmente no entiendo por qué necesitas esto.

 19
Author: AlexR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-18 10:37:53

Convertí HashMap en una cadena usando el método toString() y pasar a el otro método que toma una cadena y convertir esta cadena en HashMap objeto

Esta es una forma muy, muy mala de pasar un HashMap.

Teóricamente puede funcionar, pero hay demasiado que puede salir mal (y funcionará muy mal). Obviamente, en tu caso algo sale mal. No podemos decir qué sin ver tu código.

Pero mucho mejor solución sería cambiar ese "otro método" para que solo tome un HashMap como parámetro en lugar de una representación de cadena de uno.

 5
Author: Michael Borgwardt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-18 07:26:59

¿Qué intenta?

objectOutputStream.writeObject(hashMap);

Debería funcionar bien, siempre que todos los objetos en el HashMap implementen Serializable.

 3
Author: djna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-18 07:03:06

No se puede revertir de string a un Objeto. Así que tendrás que hacer esto:

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();
 3
Author: zengr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-18 07:22:03

No puedes hacer esto directamente, pero lo hice de una manera loca como se muestra a continuación...

La idea básica es que, primero necesita convertir la cadena de HashMap en Json, luego puede deserializar Json usando Gson/Genson, etc. en HashMap nuevamente.

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

Aplicación...

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);
 3
Author: Muhammad Suleman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-02 12:37:21

¿Está restringido a usar solo HashMap??

Por qué no puede ser tan flexible JSONObject puedes hacer mucho con él.

Puedes convertir String jsonString a 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();
}
 2
Author: Vinothkumar Arputharaj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-13 20:49:23

Es posible reconstruir una colección a partir de su presentación de cadena, pero no funcionará si los elementos de la colección no anulan su propio método toString.

Por lo tanto, es mucho más seguro y fácil usar bibliotecas de terceros como XStream que transmiten objetos en XML legible por humanos.

 0
Author: Boris Pavlović,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-18 07:11:13

Espero que realmente necesite obtener el valor de string pasando la clave hashmap. Si ese es el caso, entonces no tenemos que convertirlo de nuevo a Hashmap. Utilice el siguiente método y podrá obtener el valor como si se hubiera recuperado del propio 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;
}

Hace el trabajo por mí.

 0
Author: Ayush Goyal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-09 09:48:44

Esto puede ser ineficiente e indirecto. Pero

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

Debería funcionar !!!

 0
Author: Akash EJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-30 12:33:39