I have some value for parsing, for example :
Student{id=19, groupId=1, firstName='Alex', lastName='Sparrow'}
I want to parse this String and get new Arraylist, that will have 1,Alex,Sparrow
.
Only this data.
I want to make general parser even if comes some other object f.e. Group{id=22, groupName="BKS",groupCity="Moscow"};
I also will be able to parse it and get List BKS,groupCity,Moscow
.
Maybe I can use StringBuilder for it but I am not sure.
CodePudding user response:
In case you only want to get only attribute values. You can consider parse by key-value.
Student{id=19, groupId=1, firstName='Alex', lastName='Sparrow'}
Get the string in {}
id=19, groupId=1, firstName='Alex', lastName='Sparrow'
Then split by ",", you will get array of key=value.
Use loop to continue to split key and value by =
for(string item: data.split(",")){
String[] keyValues = item.split("=")
String key = keyValues[0];
String value = keyValues[1];
}
In case you want to convert to DTO or Pojo, You will have more step to convert key-value to object field.
you can use java reflection to set value for field by name.
https://www.oracle.com/technical-resources/articles/java/javareflection.html
CodePudding user response:
If you have string:
String string = "Student{id=19, groupId=1, firstName='Alex', lastName='Sparrow'}";
Use regular expression to clear string from whitespaces, text before {
, and {
and }
characters itself (it may need adjustments if value or key can contain whitespaces) with:
string = string.replaceAll("\\s|.*\\{|\\}","");
Create a map, which is perfect for key-value pairs, makes it easy and fast to get value based on key. Additionaly HashMap will also ensure that keys are unique:
Map<String,String> map = new HashMap<>();
Populate map with splitted string data:
for (String item : string.split(",")){
map.put(item.split("=")[0],item.split("=")[1]);
}
Now you can get your data with map.get(String key)
. For example:
map.get("groupId");
And use all map methods as described in: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html