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!

5
  • 1
    A string is already an Object. What exactly do you need? Commented Jul 2, 2017 at 2:27
  • I need to store this data and set it in InputTexts, this string can comes with more key=values Commented Jul 2, 2017 at 2:30
  • 1
    Ok, a map is your best bet. I'll write an answer Commented Jul 2, 2017 at 2:32
  • I think his real value may be more complex (maybe json) and therefore it may be a bad idea to just split at , Commented Jul 2, 2017 at 3:26
  • If the Strings are indeed JSON, then the following question will help: stackoverflow.com/questions/2591098/how-to-parse-json-in-java Commented Jul 2, 2017 at 15:10

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.