英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论