Convert HashMap.toString() back to HashMap in Java

后端 未结 12 1732
执念已碎
执念已碎 2020-12-14 00:35

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 t

12条回答
  •  星月不相逢
    2020-12-14 01:06

    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.

提交回复
热议问题