将 JSON 中的整数解码为字符串。

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

Decoding JSON int into string

问题

我有一个简单的JSON字符串,我希望在进行json.Unmarshal时将user_id转换为字符串

{"user_id": 344, "user_name": "shiki"}

我尝试了以下代码:

type User struct {
  Id       string `json:"user_id,int"`
  Username string `json:"user_name"`
}

func main() {
  input := `{"user_id": 344, "user_name": "shiki"}`
  user := User{}
  err := json.Unmarshal([]byte(input), &user)
  if err != nil {
    panic(err)
  }

  fmt.Println(user)
}

但是我得到了以下错误:

panic: json: cannot unmarshal number into Go value of type string

Playground链接:http://play.golang.org/p/mAhKYiPDt0

英文:

I have this simple JSON string where I want user_id to be converted into string when doing json.Unmarshal:

{"user_id": 344, "user_name": "shiki"}

I have tried this:

type User struct {
  Id       string `json:"user_id,int"`
  Username string `json:"user_name"`
}

func main() {
  input := `{"user_id": 344, "user_name": "shiki"}`
  user := User{}
  err := json.Unmarshal([]byte(input), &user)
  if err != nil {
    panic(err)
  }

  fmt.Println(user)
}

But I just get this error:

panic: json: cannot unmarshal number into Go value of type string

Playground link: http://play.golang.org/p/mAhKYiPDt0

答案1

得分: 62

你可以使用json.Number类型,它被实现为一个string

type User struct {
    Id       json.Number `json:"user_id"`
    Username string      `json:"user_name"`
}

然后你可以在任何其他代码中简单地转换它:

stringNumber := string(userInstance.Id)

Playground: https://play.golang.org/p/2BTtWKkt8ai

英文:

You can use the type json.Number which is implemented as a string:

type User struct {
        Id       json.Number `json:"user_id"`
        Username string      `json:"user_name"`
}

Then you can simply convert it in any other code:

stringNumber := string(userInstance.Id)

Playground: https://play.golang.org/p/2BTtWKkt8ai

huangapple
  • 本文由 发表于 2014年6月30日 06:27:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/24480835.html
匿名

发表评论

匿名网友

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

确定