简体   繁体   English

GSON /如何解析数字

[英]GSON / How to parse a number

I want to parse JSON-documents with GSON. 我想用GSON解析JSON文档。 However, I have a problem with numbers. 但是,我对数字有疑问。

My pattern is simply iterating over all tokens... that is first peeking and then doing stuff based on the TokenType in a switch-statement. 我的模式只是简单地遍历所有令牌……这是先窥视然后基于切换语句中的TokenType做一些事情。 The reader in the following code snippet is a JsonReader . 以下代码段中的readerJsonReader

while (reader.hasNext() && !endReached) {
  final var nextToken = reader.peek();

  switch (nextToken) {
    case NUMBER:
      // reader.nextInt(), reader.nextLong(), reader.nextDouble()
      break;
    ...
  }
}

How do I know if it's an Integer/Long or a decimal value, maybe only fitting into a BigDecimal? 我怎么知道它是Integer / Long还是十进制值,也许只适合BigDecimal? Just calling nextString() and then try to parse the String with BigDecimal and so on? 只是调用nextString(),然后尝试使用BigDecimal解析字符串,依此类推?

In JSON , numbers are always floating-point numbers of the form JSON中 ,数字始终是形式的浮点数
['-'] digits [ '.' digits ] [ 'e' sign digits ]

So basically a double , except NaN and ±Infinity . 所以基本上是double ,除了NaN±Infinity

For generic code use nextDouble() , unless you expect very large numbers, where BigDecimal needs to be used. 对于通用代码,请使用nextDouble() ,除非您期望非常大的数字(需要使用BigDecimal

The nextInt() and nextLong() method are helper methods for when you know the number is supposed to be an integer value. 当您知道数字应该为整数值时, nextInt()nextLong()方法是辅助方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM