0

i have a question using a String with this format in Java(Android):

"{ key1 = value2, key2 = value2 }"

What's the best way to convert this String into Object?

I appreciate any help!

jagapathi
  • 1,635
  • 1
  • 19
  • 32
Johan Sánchez
  • 165
  • 3
  • 17

1 Answers1

1
HashMap<String, String> getMap(String rawData) {
    HashMap<String, String> map = new HashMap<>();
    String[] pairs = rawData.split(","); // split into key-value pairs
    for(String pair: pairs) {
        pair = pair.trim(); // get rid of extraneous white-space
        String[] components = pair.split("="); 
        String key = components[0].trim();
        String value = components[1].trim();
        map.put(key, value); // put the pair into the map
    }
    return map;
}

You can use it like this:

HashMap<String, String> map = getMap("key1 = value1, key2 = value2");
String valueForKey1 = map.get("key1"); // = value1
Dziugas
  • 1,500
  • 1
  • 12
  • 28