Cata D Cata D - 3 months ago 7
Java Question

Convert comma separated key=value pairs to Java object

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?

Answer

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.

Comments