Roee Roee - 2 months ago 6
Java Question

String[] array length isnt equal to the actual number of elements inside it

I have a big project im working on, there is a piece of code where i get 2 arrays of String from an http post request on my server using spring and hibernate (json format), when i print the arrays size i get 1 in return, but at the same time i have (as i should/want/expect) 2 elements inside it so when i iterate over the array with the expected length i get an "array out of bound exception" and that's really weird imo.

p.s. - this problem repeats itself in other places as well, maybe its has something to do with hibernate/spring?.

output:

deviceAaddr - size = 1, [0022C01504D3,0022C015050F]
devicePass - size = 1, [HOMI26,HOMI26]


json:

{"deviceAddr":["0022C01504D3,0022C015050F"],"devicePass":["HOMI26,HOMI26"],"deviceCount":2,"version":"MU18"}


code:

public class AddBatchObject {

private String[] deviceAddr;

public String[] getDeviceAddr() {
return deviceAddr;
}

@Override
public String toString() {
String batch = "";
if (deviceAddr != null){
batch += "deviceAaddr - " + "size = " + deviceAddr.length + ", "
+ Arrays.asList(deviceAddr).toString() + "\n";
}
if (devicePass != null){
batch += "devicePass - " + "size = " + devicePass.length + ", " +
Arrays.asList(devicePass).toString() + "\n";
}
return batch;
}

}


rest controller:

@RequestMapping(value = "/add/mac",method = RequestMethod.POST, produces = "application/json")
public @ResponseBody Object addMac(@RequestBody AddBatchObject addBatchObject, HttpServletRequest request) throws AuthenticationException{
LoggerUtils.getLogger().info("addMac");
return AdminAddMac.adminAddMac(addBatchObject,request);
}



Edit: as jtahlborn and Joe answered the json data was
incorrect: ["0022C01504D3,0022C015050F"] is a single element array. a
two element array would be ["0022C01504D3","0022C015050F"].

Answer

The output is correct. Your JSON contains one string that has a comma in it, rather than two distinct strings.

The JSON you probably want is:

{"deviceAddr":["0022C01504D3","0022C015050F"],"devicePass":["HOMI26","HOMI26"],"deviceCount":2,"version":"MU18"}
Comments