Lokesh Cherukuri Lokesh Cherukuri - 11 months ago 42
Java Question

Convert string of values into an object in Java

I have a string like

. I want to retrieve those values by property name.

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

Is there way to retrieve those values by each property like


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("=");

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: