Gson强制使用int而不是double [英] Gson force use int instead of double

查看:829
本文介绍了Gson强制使用int而不是double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我可以配置gson,他使用int而不是double获得像这样的数据:

Hi can i configure gson that he use int instead of double got data like:

{fn: chat, data: {roomId: 1, text: "Some brabble"}}

我得到一个PacketClass将其反序列化为:

I got a PacketClass to deserialize it to:

public class DataPacket {
  private String fn;
  private Object p; // will be a StringMap
}

并解码为:

DataPacket pkg = gson.fromJson(message, DataPacket.class);

为了更好的处理类型,我为DataPacket.p字段获得了一个数据pojo,例如:

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
}

将数据解析为我使用BeanMaps的数据包(我删除了错误处理等):

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();
}

现在问题在于gson使roomId:1变为1.0的1.0倍StringMap和Beanmap尝试将其解析为一个整数并抛出一个NumberFormatException,任何人都知道如何解决这个问题?

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?

谢谢!

推荐答案

我认为您可以简单地将您的DataPacket类更改为

I think you could simply change your DataPacket class to

public class DataPacket {
  private String fn;
  private ChatPacket p; // will be a StringMap
}

(用ChatPacket替换Object) - 如果进入你的应用程序的其余部分。然后,Gson将识别ChatPacket类的数据类型,并将1作为int。

(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 :-( )

您可以使用Gson和它的低级帮手JsonParser的组合:

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);

这篇关于Gson强制使用int而不是double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆