猿问

当我在转换“Id”后将 [] 字节解组为结构时出现 json 问题不正确

当我在转换“Id”不正确后将 [] 字节解组为结构时,我遇到了 json 问题

编号:1606146401088049402 => 1606146401088049400


`{"status":200,"success":true,"data":{"id":1606146401088049402,"created_at":"2020-11-23T22:46:41.092+07:00","updated_at":"2020-11-23T22:46:41.092+07:00","role":[{"code":"admin","name":"admin"}],"userName":"","phone":"0385666301","email":"congnguyen008@gmail.com","name":"","gender":"","title":"","firstName":"Nguyên","lastName":"Nguyễn","fullName":"Nguyên Nguyễn","displayName":"Nguyên Nguyễn","company":"","department":"","photo":"0385666301","addresses":"","phoneNumber":"","active":true,"lastTimeLogin":"2020-12-23T09:27:30.72+07:00","logged":{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDg2OTQwNTAsImlkIjoiMTYwNjE0NjQwMTA4ODA0OTQwMiIsIm5hbWUiOiJOZ3V5w6puIE5ndXnhu4VuIiwicm9sZSI6W3siY29kZSI6ImFkbWluIiwibmFtZSI6ImFkbWluIn1dfQ.Spj_wWPxRrs2tYYhCmNCWaZVWVack74k9ab1FpeQsf8","time_login":"2020-12-23 09:27:30.720385 +0700 +07 m=+56.589410521","refresh_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDkyOTUyNTAsImlkIjoiMTYwNjE0NjQwMTA4ODA0OTQwMiIsIm5hbWUiOiJOZ3V5w6puIE5ndXnhu4VuIiwicm9sZSI6W3siY29kZSI6ImFkbWluIiwibmFtZSI6ImFkbWluIn1dfQ.mO08BTq9SUns7OPCOrDeUbZojYkw3tjUaMeIQ_e2e2U"}}}`

代码


https://play.golang.org/p/MKmkLGPfwFa


func main() {

    jsonData := `{"status":200,"success":true,"data":{"id":1606146401088049402}}`

    response := Response{}

    err := json.Unmarshal([]byte(jsonData), &response)


    if err != nil {

        panic(err)

    }


    user := User{}


    userJson, _ := json.Marshal(response.Data)


    json.Unmarshal(userJson, &user)


    fmt.Println(user.Id)

    fmt.Printf("%T", user.Id)

}


type User struct {

    Id       int64  `json:"id" gorm:"primarykey"`

    UserName string `json:"userName"`

}



茅侃侃
浏览 82回答 2
2回答

杨__羊羊

如果你想推迟 json 处理.. 而不是使用接口,编组然后解组,你可以使用json.RawMessage,像这样:https://play.golang.org/p/LR1OXWpk_sF这消除了Marshal操作和错误类型转换的问题。

翻阅古今

要将 JSON 解组为接口值,Unmarshal 将其中之一存储在接口值中:float64,用于 JSON 数字float64 类型产生错误的解组。https://golang.org/pkg/encoding/json/#Unmarshaltype Response struct {    Status  int         `json:"status"`    Success bool        `json:"success"`    Data    Datam       `json:"data,omitempty"`    Message string      `json:"message,omitempty"`    Input   interface{} `json:"input,omitempty"`    Error   error       `json:"error,omitempty"`    Paging  interface{} `json:"paging,omitempty"`}type Datam struct{    Id int64 `json:"id"`}正确解组给定的 id。
随时随地看视频慕课网APP

相关分类

Go
我要回答