I have a response String as shown below which I need to parse it and store it my class. Format is shown below:
- task name followed by this dotted line
-------------
which is also fixed - and then just below
key:value
pair. It can have many key value pair
Below is the response string.
abc-------------
Load:79008
Peak:4932152
def-------------
Load:79008
Peak:4932216
ghi-------------
Load:79008
Peak:4874588
pqr-------------
Load:79008
Peak:4874748
Below is my class:
public class NameMetrics {
private String name;
private Map<String, String> metrics;
// setters and getters
}
In the above class, name
should be abc
and metrics
map should have Load
as the key and 79008
as the value and same with other key:value
pairs. Below is the code I have.
String response = restTemplate.getForObject(url, String.class);
BufferedReader reader = new BufferedReader(new StringReader(response));
NameMetrics current = null;
Map<String, String> metricsHolder = null;
List<NameMetrics> result = new ArrayList<>();
while (true) {
String s = reader.readLine();
if (s == null) {
break; // end reached
}
if (s.trim().isEmpty()) {
continue; // Skip empty line
}
int cut = s.indexOf(':');
if (cut == -1) {
cut = s.indexOf('-');
if (cut == -1) {
continue;
}
metricsHolder = new HashMap<String, String>();
current = new NameMetrics();
current.setName(s.substring(0, cut));
result.add(current);
} else if (current != null) {
metricsHolder.put(s.substring(0, cut), s.substring(cut + 1));
current.setMetrics(metricsHolder);
}
}
I'd like a code review to see whether this can be improved in any way?