将JSON整数反序列化为空接口会导致错误的类型断言。

huangapple go评论83阅读模式
英文:

Unmarshaling a JSON integer to an empty interface results in wrong type assertion

问题

我有这段代码。我期望接口被断言为int类型。然而,接口的类型却是float64。有人能解释为什么会发生这种情况吗?有什么好的方法可以规避这个问题。

package main

import (
	"fmt"
	"encoding/json"
)

type obj struct {
	X interface{}
}

func main() {
	var x int
	x = 5
	o := &obj {
		X: x,
	}
	b, _ := json.Marshal(o)
	var newObj obj
	json.Unmarshal(b, &newObj)
	if _, ok := newObj.X.(int); ok {
		fmt.Println("X is an int")
	} else if _, ok := newObj.X.(float64); ok {
		fmt.Println("X is a float64")
	} else {
		fmt.Println("This does not make any sense")
	}
}

这段代码输出"X is a float64"。你可以在这里运行代码:https://play.golang.org/p/9L9unW8l3n

英文:

I have this code. I expect the interface to be type asserted to int. However, the type of the interface is float64 instead. Can anyone explain why this is happening? And what are the best ways to circumvent it.

package main

import (
    "fmt"
    "encoding/json"
)

type obj struct {
    X interface{}
}

func main() {
    var x int
    x = 5
    o := &obj {
	    X: x,
    }
    b, _ := json.Marshal(o)
    var newObj obj
    json.Unmarshal(b, &newObj)
    if _, ok := newObj.X.(int); ok {
	    fmt.Println("X is an int")
    } else if _, ok := newObj.X.(float64); ok {
	    fmt.Println("X is a float64")
    } else {
	    fmt.Println("This does not make any sense")
    }
}

This code prints "X is a float64". You can run the code there https://play.golang.org/p/9L9unW8l3n

答案1

得分: 5

数字被编码为"Json numbers",Unmarshal将Json numbers解码为浮点数。根据文档:

Marshal

浮点数、整数和Number值被编码为JSON数字。

Unmarshal

为了将JSON解组为接口值,Unmarshal将以下之一存储在接口值中:

bool,用于JSON布尔值
float64,用于JSON数字
string,用于JSON字符串
[]interface{},用于JSON数组
map[string]interface{},用于JSON对象
nil,用于JSON null

英文:

Numbers are encoded as "Json numbers" Unmarshal decodes Json numbers as floats. From the docs:

Marshal
> Floating point, integer, and Number values encode as JSON numbers.

Unmarshal
> 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

huangapple
  • 本文由 发表于 2016年8月26日 02:33:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/39152481.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定