【问题标题】:JSON Simple: integer parsingJSON Simple:整数解析
【发布时间】:2015-04-21 11:00:52
【问题描述】:

我在 REST 服务中解析 JSON 整数时遇到问题。解析字符串和双精度类型工作正常

工作:

JSONParser parser = new JSONParser();
Object obj = null;
try {
    obj = parser.parse(input);
} catch (ParseException e) {
    e.printStackTrace();
}
JSONObject jsonObject = (JSONObject) obj;   

//---------------
String uName = (String) jsonObject.get("userName");
double iPrice = (Double) jsonObject.get("itemPrice");

不工作:

int baskId = (Integer) jsonObject.get("basketId");

我尝试将我的购物篮类中的basketId 转换为字符串,然后它运行正常,所以代码正常,并且链接工作,但是,当我将它转换回 int 时,我得到 500 服务器错误。我正在使用它来创建一个带有一些数字 ID 的新篮子,因此我使用了 @POST 注释,并且负载中的 JSON 如下:

{"basketId":50}

我不明白...

编辑: 我明白了...JSON simple 只接受更大类型的 Java 原语,所以整数和浮点数是不行的

【问题讨论】:

  • 什么是错误信息?
  • 你使用什么库?它没有getInt(...) 方法吗?
  • 它的JSON简单库,code.google.com/p/json-simple,没有getInt,直接get。双被解析得很好。我正在使用 chrome rest 客户端插件,所以我收到 500 内部服务器错误。 eclipse没有错误
  • 在这种情况下,您必须在转换之前检查值 basketId 的类型。你可以使用instanceofjsonObject.get("basketId").getClass()

标签: java json rest post


【解决方案1】:

在你的代码中jsonObject.get("basketId");returns Long

因此,使用 Long 进行类型转换将帮助您解决错误 (Long)jsonObject.get("basketId");

如果您确实需要 Integer,请按如下方式将其强制转换为 inetger

((Long)jsonObject.get("basketId")).intValue()

【讨论】:

  • 这确实有效......嗯...... JSON Simple 可能只接受更大的类型,因为我刚刚尝试使用 float,但它也不起作用。
【解决方案2】:

如果你把它解析为字符串,你不能做这样的事情:

String x = "10";
int y = (int) x;

但是你可以使用这个方法

String x = "10";
int y = Integer.valueOf(x);

【讨论】:

  • 这对我没有好处,因为篮子构造函数是 Basket(int basketId)...我必须在客户端设置各种限制,并进行双向转换跨度>
  • 好吧,我们可以使用jackson,而不是自动完成反序列化
【解决方案3】:

而不是:int baskId = (Integer) jsonObject.get("basketId");

使用:int baskId = jsonObject.getInt("basketId");

在官方文档中:http://www.json.org/javadoc/org/json/JSONObject.html#getInt(java.lang.String)

【讨论】:

  • 他不使用那个库,他使用code.google.com/p/json-simple,在这个库中JSONObject只是Map的扩展,它没有getInt(...)方法。跨度>
猜你喜欢
  • 2015-11-11
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 2016-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多