首页 > 解决方案 > 为什么golang json number不能像“10”那样转换int或string int?

问题描述

我想将接口值转换为数字,但是当接口是数字或数字字符串时,它不起作用,我不知道为什么我们不能这样转换?

package main

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

func main() {
    number := 10
    strNumber := "10"
    test(number)
    test(strNumber)
}

func test(i interface{}) {
    strNum, ok := i.(json.Number)
    fmt.Println(strNum, ok, reflect.TypeOf(i))
}

它将产生如下结果:

   false int
   false string

标签: jsongotype-conversion

解决方案


这是您在 Go 中的示例:

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

func main() {
    number := 10
    strNumber := "10"
    test(number)
    test(strNumber)
}

func test(i interface{}) {
    var strNum string
    switch x := i.(type) {
    case int:
        strNum = strconv.Itoa(x)
    case string:
        if _, err := strconv.ParseInt(x, 10, 64); err == nil {
            strNum = x
        }
    }
    jsonNum := json.Number(strNum)
    fmt.Printf("%[1]v %[1]T\n", jsonNum)
}

游乐场: https: //play.golang.org/p/iDSxrORX9yc

输出:

10 json.Number
10 json.Number

推荐阅读