Hi can i configure gson that he use int instead of double got data like:
{fn: chat, data: {roomId: 1, text: "Some brabble"}}
I got a PacketClass to deserialize it to:
public class DataPacket {
private String fn;
private Object p; // will be a StringMap
}
and decode like:
DataPacket pkg = gson.fromJson(message, DataPacket.class);
for better typehandling i got a data pojo for the DataPacket.p field for example:
public class ChatPacket {
public int roomId;
public String message;
public String from;
// getter & setter
}
to parse the data to the packet i use BeanMaps like (i removed error handling etc):
public Object getData(Class<?> pojoClass) {
pojo = pojoClass.newInstance();
BeanMap b = new BeanMap();
b.setBean(pojo);
b.putAll(this.p);
pojo = b.getBean();
}
The problem is now that gson make the roomId: 1 to a double 1.0 in the StringMap and the beanmap try to parse it to an integer and throws a NumberFormatException, anyone got an idea how to fix this?
Thank You!
I think you could simply change your DataPacket class to
public class DataPacket {
private String fn;
private ChatPacket p; // will be a StringMap
}
(replace Object by ChatPacket) - if that suits into the rest of your application. Gson will then recognize the data types of the ChatPacket class and will trait the "1" as int.
EDIT (as you can't use full formatting features in comments :-( )
You can use a combination of Gson and it's low level helper JsonParser like this:
String testStr = "{fn: chat, data: {roomId: 1, message: \"Some brabble\"}}";
DataPacket dp = new Gson().fromJson(testStr, DataPacket.class);
JsonParser parser = new JsonParser();
JsonElement e = parser.parse(testStr);
ChatPacket cp = new Gson().fromJson(e.getAsJsonObject().getAsJsonObject("data"), ChatPacket.class);