英文:
How to convert JSON string to struct
问题
我开始使用golang工作,我试图将JSON字符串解析为结构体,但是它不起作用。
JSON字符串:
> dailies":[{"userAccessToken":"acessToken","uploadStartTimeInSeconds":1499744832,"uploadEndTimeInSeconds":1499744832,"callbackURL":"callbackurl"}]}
type pingDataFormat struct {
userAccessToken string
uploadStartTimeInSeconds int
uploadEndTimeInSeconds int
callbackURL string
}
以下是将JSON字符串转换为结构体的代码
pingJSON := make(map[string][]pingDataFormat)
err := json.Unmarshal([]byte(pingData), &pingJSON)
if err != nil {
panic(err)
}
fmt.Printf("\n\n json object:::: %v", pingJSON)
输出结果为:
> json object:::: map[dailies:[{ 0 0 }]]
这里的"dailies"没有数据,所以我是否按照正确的方法进行解析?如何在解析后获取数据?
英文:
I have start working in golang, I am trying to parse JSON string to struct but its not working.
JSON String:
> dailies":[{"userAccessToken":"acessToken","uploadStartTimeInSeconds":1499744832,"uploadEndTimeInSeconds":1499744832,"callbackURL":"callbackurl"}]}
type pingDataFormat struct {
userAccessToken string
uploadStartTimeInSeconds int
uploadEndTimeInSeconds int
callbackURL string
}
Below is code which convert JSON String to structs
pingJSON := make(map[string][]pingDataFormat)
err := json.Unmarshal([]byte(pingData), &pingJSON)
if err != nil {
panic(err)
}
fmt.Printf("\n\n json object:::: %v", pingJSON)
output is:
> json object:::: map[dailies:[{ 0 0 }]]
Here "dailies" dont have data, So do i following right approach to parse and how to get data after parse?
答案1
得分: 18
pingDataFormat
中的字段需要被导出(以大写字母开头)
type pingDataFormat struct {
UserAccessToken string `json:"userAccessToken"`
UploadStartTimeInSeconds int `json:"uploadStartTimeInSeconds"`
UploadEndTimeInSeconds int `json:"uploadEndTimeInSeconds"`
CallbackURL string `json:"callbackURL"`
}
这样应该可以解决你的问题。
https://play.golang.org/p/Z3yszFl01L
英文:
The fields in pingDataFormat
need to be exported (start with a capital letter)
type pingDataFormat struct {
UserAccessToken string `json:"userAccessToken"`
UploadStartTimeInSeconds int `json:"uploadStartTimeInSeconds"`
UploadEndTimeInSeconds int `json:"uploadEndTimeInSeconds"`
CallbackURL string `json:"callbackURL"`
}
That should solve your problem
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论