Golang嵌套结构体使用下划线进行解组。

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

Golang nested structs unmarshaling with underscores

问题

我正在使用Instagram API编写一个应用程序。
我收到一个JSON请求,然后将其解析为嵌套结构。

// 嵌套结构
type ResponseData struct {
ID string json:"id"
Link string json:"link"
Type string json:"type"
User struct {
FullName string json:"full_name"
ID int json:"id"
ProfilePicture string json:"profile_picture"
Username string json:"username"
}
Images struct {
Standard_Resolution struct {
URL string json:"url"
}
}
}

为了添加图像URL,它需要在Standard_Resolution中有下划线,我正在使用Atom的Go Plus包,并且我收到了一个lint警告:

不要在Go名称中使用下划线;结构字段Standard_Resolution应该是StandardResolution

是否有其他方法可以修复错误并仍然在我的结构中保留该值。

更新:

我可以在StandardResolution的最后一个大括号后面添加一个标识符。

StandardResolution struct {
URL string json:"url"
} json:"standard_resolution"

英文:

I am writing an app using the Instagram API.
I am receiving a JSON request and that gets Unmarshal'ed into nested structs.

// the nested structs
type ResponseData struct {
    ID   string `json:"id"`
    Link string `json:"link"`
    Type string `json:"type"`
    User struct {
	    FullName       string `json:"full_name"`
	    ID             int    `json:"id"`
	    ProfilePicture string `json:"profile_picture"`
	    Username       string `json:"username"`
    }
    Images struct {
	    Standard_Resolution struct {
		    URL string `json:"url"`
	    }
    }
}

For the Image url to be added it needs to have the underscore in Standard_Resolution , I am using Go Plus Package for Atom and I get the lint warning:

> don't use underscores in Go names; struct field Standard_Resolution
> should be StandardResolution

Is there another way for me fix the error and still have the value in my struct.

Update:

I can add an identifier after the last brace for StandardResolution.

StandardResolution struct {
    URL string `json:"url"`
} `json:"standard_resolution"`

答案1

得分: 2

无论如何,如果不使用嵌套结构,阅读起来会更容易。

type RDUser struct { ... }
type RDStandardResolution struct { ... }
type RDImages struct {
    StandardResolition RDStandardResolution `json:"standard_resolution"`
}
type ResponseData struct {
    ...
    User RDUser `json:"user"`
    Images RDImages `json:"images"`
}
英文:

Anyway it is easier to read if you don't use nested structs.

type RDUser struct { ... }
type RDStandardResolution struct { ... }
type RDImages struct {
    StandardResolition RDStandardResolution `json:"standard_resolution"`
}
type ResponseData struct {
    ...
    User RDUser `json:"user"`
    Images RDImages `json:"images"`
}

huangapple
  • 本文由 发表于 2015年7月3日 06:32:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/31195707.html
匿名

发表评论

匿名网友

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

确定