如何将JSON字符串转换为结构体(struct)?

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

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

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

huangapple
  • 本文由 发表于 2017年7月29日 15:30:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/45386644.html
匿名

发表评论

匿名网友

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

确定