Lokesh Cherukuri Lokesh Cherukuri - 4 months ago 9
Java Question

Convert string of values into an object in Java

I have a string like

"name=lokesh,age=25"
. I want to retrieve those values by property name.

I tried converting it to a
JsonObject
by using Google Gson. But it threw an error because it is not valid
JsonObject
.

Is there way to retrieve those values by each property like
Obj.get("name")
etc

Answer

You may convert the String into a Map:

String str = "name=lokesh,age=25";
Map<String,String> map = new HashMap<String,String>();
for(String keyValueStr: str.split(",")){
     String[] keyValue = keyValueStr.split("=");
     map.put(keyValue[0],keyValue[1]);
 }

Then, you are free to access the values by keys

String name = map.get("name");

Or using guava's Splitter (I wouldn't add the dependency just for that):

String str = "name=lokesh,age=25";
Map<String, String> map = Splitter.on(",").withKeyValueSeparator("=").split(str);

With the following dependency:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>17.0</version>
</dependency>
Comments