#114 float[] conversion fails

open
nobody
None
5
2011-02-09
2011-02-09
Alphonse Bendt
No

In my Javaclass i have:

private float[] floatArray;

public void setFloatArray(float[] values) {
floatArray = values;
}

public float[] getFloatArray() {
return floatArray;
}

we use a simple abstraction on top of json lib. it provides these two methods:

public <T> T toBean(String json, Class<T> clazz) throws ParseException {
try {
JSONObject jsonObject = JSONObject.fromObject(json);
return (T) JSONObject.toBean(jsonObject, clazz);

} catch (net.sf.json.JSONException e) {
e.printStackTrace();
throw new ParseException(json, 0);
}
}

public String toJSON(Object bean) {
if (bean == null) {
return EMPTY_JSON;
}
JSONObject jsonObject = JSONObject.fromObject(bean, JSON_CONFIG);
return jsonObject.toString();
}

the following test fails:

float[] floatArray = new float[] {1f, 1.5F, 10.5F};

MyBean bean = new MyBean();
bean.setFloatArray(floatArray);

String json = objectUnderTest.toJSON(bean);

MyBean fromJson = objectUnderTest.toBean(json, MyBean.class);

Assert.assertArrayEquals(floatArray, fromJson.getFloatArray(), .1F);

as it seems the object can be converted to json but the way back fails.

this is the exception:

net.sf.json.JSONException: Error while setting property=floatArray type interface java.util.List

Discussion

  • Alphonse Bendt
    Alphonse Bendt
    2011-02-09

    tried using json-lib 2.3 and 2.4