dongwo1234 2015-05-07 15:35
浏览 282
已采纳

不同类型反射的Golang JSON数组:float64 vs int64

Consider this simple example:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "reflect"
)

var args = `[1, 2.5, "aaa", true, false]`

func main() {
    var x []interface{}
    err := json.Unmarshal([]byte(args), &x)

    if err != nil {
        log.Fatalf("%s", err.Error())
        panic(fmt.Sprintf("%s", err.Error()))
    }

    for _, arg := range x {
        t := reflect.TypeOf(arg).Kind().String()
        v := reflect.ValueOf(arg)

        if t == "int64" {
            fmt.Printf("int64 %v
", v.Int())
        }

        if t == "float64" {
            fmt.Printf("float64 %v
", v.Float())
        }

        if t == "string" {
            fmt.Printf("string %v
", v.String())
        }

        if t == "bool" {
            fmt.Printf("bool %v
", v.Bool())
        }
    }
}

The program outputs:

float64 1
float64 2.5
string aaa
bool true
bool false

As you can see, my input is a valid JSON which represents an array with five items:

- integer
- floating point number
- string
- boolean
- boolean

When I unmarshal the valid JSON string into []interface{} and try to check the types with reflection, the integer value from JSON has a type of float64. Any idea why? Is this expected behaviour?

  • 写回答

2条回答 默认 最新

  • duanjiao3754 2015-05-07 15:39
    关注

    This is documented behavior of Unmarshal. All numbers are unmarshaled into float64.

    To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

    • bool, for JSON booleans
    • float64, for JSON numbers
    • string, for JSON strings
    • []interface{}, for JSON arrays
    • map[string]interface{}, for JSON objects
    • nil for JSON null

    This is because JSON does not have integers, every number in JSON is defined to be a 64 bit floating point.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?