Cata D Cata D - 1 year ago 111
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:


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 Source

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download