Golang在从JSON转换整数时出现错误。

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

Golang json error convertering int from json

问题

我正在尝试对下面的代码进行简单的解组和提取整数信息。我在另一个stackoverflow上找到了一个链接:链接。然而,在我的情况下它并没有帮助。根据ideone的程序,数据被认为是一个浮点数。

package main
import "fmt"
import "encoding/json"

func main(){
    byt := []byte(`{"status": "USER_MOVED_LEFT", "id":1, "x":5, "y":3}`)
    var dat map[string]interface{}
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    num := dat["id"].(int)
    fmt.Println(num)
}
英文:

I'm trying to do a simple unmarshall and extracting the int information from the code below. I found a link from another stackoverflow : link. Though, it doesn't help in my case. the program according to ideone think the data is a float.

package main
import "fmt"
import "encoding/json"

func main(){
	byt := []byte(`{"status": "USER_MOVED_LEFT", "id":1, "x":5, "y":3}`)
	var dat map[string]interface{}
	if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    num := dat["id"].(int)
    fmt.Println(num)
}

答案1

得分: 4

如果你将byt转换为map[string]interface{},数字的默认值将是float64

func main(){
    byt := []byte(`{"status": "USER_MOVED_LEFT", "id":1, "x":5, "y":3}`)
    var dat map[string]interface{}
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    
    fmt.Println(reflect.TypeOf(dat["id"])) // 打印值的类型
    num := dat["id"].(float64)
    fmt.Println(num)
}

但你也可以通过将数据byt转换为struct来改变这种行为,如下所示:

type myStruct struct {
    Status string
    Id     int
    x      int
    y      int
}

func main() {
    byt := []byte(`{"status": "USER_MOVED_LEFT", "id":1, "x":5, "y":3}`)
    dat := myStruct{}
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }

    fmt.Println(reflect.TypeOf(dat.Id))
    fmt.Printf("%+v\n", dat.Id)
}
英文:

If you are converting your byt to map[string]interfaec{} the default value of the number will be float64.

func main(){
    byt := []byte(`{"status": "USER_MOVED_LEFT", "id":1, "x":5, "y":3}`)
    var dat map[string]interface{}
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    
    fmt.Println(reflect.TypeOf(dat["id"])) // print the type of value
    num := dat["id"].(float64)
    fmt.Println(num)
}

But you can also change this behavior by converting your byt which is your data to a struct like this :

type myStruct struct {
	Status string
	Id     int
	x      int
	y      int
}

func main() {
	byt := []byte(`{"status": "USER_MOVED_LEFT", "id":1, "x":5, "y":3}`)
	dat := myStruct{}
	if err := json.Unmarshal(byt, &dat); err != nil {
		panic(err)
	}

	fmt.Println(reflect.TypeOf(dat.Id))
    fmt.Printf("%+v\n", dat.Id)

}

huangapple
  • 本文由 发表于 2017年7月19日 06:05:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/45177878.html
匿名

发表评论

匿名网友

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

确定