Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert comma separated key=value pairs to Java object

Tags:

java

csv

I'm trying to implement a HttpMessageConverter which would allow my program to talk over REST to an embedded smart controller.

The controller responds with strings such as:

ret=OK,htemp=27.0,hhum=-,otemp=27.0,err=0,cmpfreq=24

I have a Java object called SensorInfo.

public class SensorInfo {

   String ret;
   Double htemp;
   String hhum;
   Double otemp;
   Integer err;
   Integer cmpfreq;

   // getters and setters

}

What's the best way of mapping the controller response to the above Java object?

like image 802
Cata D Avatar asked Aug 23 '26 21:08

Cata D


1 Answers

You can simply split the string and assign each element as needed. You have:

ret=OK,htemp=27.0,hhum=-,otemp=27.0,err=0,cmpfreq=24

Lets assume you have that stored in a variable called myStr. Then all you need to do is this:

String[] strSplit = myStr.split(" ");
SensorInfo info = new SensorInfo();
info.ret = afterEquals(strSplit[0]);
info.htemp = Double.parse(afterEquals(strsplit[1]));
info.hhum = afterEquals(strSplit[2]);
info.otemp= Double.parse(afterEquals(strSplit[3]));
info.err = Integer.parse(afterEquals(strSplit[4]));
info.cmpfreq = Integer.parse(afterEquals(strSplit[5]));

You will declare a method to extract the part of the response after the equals sign to make the above work:

private String afterEquals(String input) {
  input.substring(input.indexOf('=') + 1);
}

Note that this assumes the order of your response is fixed. If it isn't, you can easily modify this to look at each argument to see which variable to assign it to.

like image 168
nhouser9 Avatar answered Aug 26 '26 12:08

nhouser9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!