golang从JSON自动生成Go结构体定义插件库gojson的使用
golang从JSON自动生成Go结构体定义插件库gojson的使用
gojson是一个可以从JSON或YAML文档生成Go结构体定义的工具。
示例
$ curl -s https://api.github.com/repos/chimeracoder/gojson | gojson -name=Repository
package main
type Repository struct {
ArchiveURL string `json:"archive_url"`
AssigneesURL string `json:"assignees_url"`
BlobsURL string `json:"blobs_url"`
BranchesURL string `json:"branches_url"`
CloneURL string `json:"clone_url"`
CollaboratorsURL string `json:"collaborators_url"`
CommentsURL string `json:"comments_url"`
CommitsURL string `json:"commits_url"`
CompareURL string `json:"compare_url"`
ContentsURL string `json:"contents_url"`
ContributorsURL string `json:"contributors_url"`
CreatedAt string `json:"created_at"`
DefaultBranch string `json:"default_branch"`
Description string `json:"description"`
DownloadsURL string `json:"downloads_url"`
EventsURL string `json:"events_url"`
Fork bool `json:"fork"`
Forks float64 `json:"forks"`
ForksCount float64 `json:"forks_count"`
ForksURL string `json:"forks_url"`
FullName string `json:"full_name"`
GitCommitsURL string `json:"git_commits_url"`
GitRefsURL string `json:"git_refs_url"`
GitTagsURL string `json:"git_tags_url"`
GitURL string `json:"git_url"`
HasDownloads bool `json:"has_downloads"`
HasIssues bool `json:"has_issues"`
HasWiki bool `json:"has_wiki"`
Homepage interface{} `json:"homepage"`
HooksURL string `json:"hooks_url"`
HtmlURL string `json:"html_url"`
ID float64 `json:"id"`
IssueCommentURL string `json:"issue_comment_url"`
IssueEventsURL string `json:"issue_events_url"`
IssuesURL string `json:"issues_url"`
KeysURL string `json:"keys_url"`
LabelsURL string `json:"labels_url"`
Language string `json:"language"`
LanguagesURL string `json:"languages_url"`
MasterBranch string `json:"master_branch"`
MergesURL string `json:"merges_url"`
MilestonesURL string `json:"milestones_url"`
MirrorURL interface{} `json:"mirror_url"`
Name string `json:"name"`
NetworkCount float64 `json:"network_count"`
NotificationsURL string `json:"notifications_url"`
OpenIssues float64 `json:"open_issues"`
OpenIssuesCount float64 `json:"open_issues_count"`
Owner struct {
AvatarURL string `json:"avatar_url"`
EventsURL string `json:"events_url"`
FollowersURL string `json:"followers_url"`
FollowingURL string `json:"following_url"`
GistsURL string `json:"gists_url"`
GravatarID string `json:"gravatar_id"`
HtmlURL string `json:"html_url"`
ID float64 `json:"id"`
Login string `json:"login"`
OrganizationsURL string `json:"organizations_url"`
ReceivedEventsURL string `json:"received_events_url"`
ReposURL string `json:"repos_url"`
SiteAdmin bool `json:"site_admin"`
StarredURL string `json:"starred_url"`
SubscriptionsURL string `json:"subscriptions_url"`
Type string `json:"type"`
URL string `json:"url"`
} `json:"owner"`
Private bool `json:"private"`
PullsURL string `json:"pulls_url"`
PushedAt string `json:"pushed_at"`
Size float64 `json:"size"`
SshURL string `json:"ssh_url"`
StargazersURL string `json:"stargazers_url"`
StatusesURL string `json:"statuses_url"`
SubscribersURL string `json:"subscribers_url"`
SubscriptionURL string `json:"subscription_url"`
SvnURL string `json:"svn_url"`
TagsURL string `json:"tags_url"`
TeamsURL string `json:"teams_url"`
TreesURL string `json:"trees_url"`
UpdatedAt string `json:"updated_at"`
URL string `json:"url"`
Watchers float64 `json:"watchers"`
WatchersCount float64 `json:"watchers_count"`
}
CLI安装
$ go get github.com/ChimeraCoder/gojson/gojson
假设$GOPATH/bin
在你的PATH
中,你现在可以直接调用gojson
。
API安装
$ go get github.com/ChimeraCoder/gojson/gojson
开发
$ git clone https://github.com/ChimeraCoder/gojson.git
$ cd gojson
$ go test
构建CLI
$ go build -o _build/gojson ./gojson
安装CLI
$ go install ./gojson
格式化
$ gofmt -w -e -s -l .
相关项目
许可证
gojson是根据GNU公共许可证第3版发布的自由软件。
在撰写本文时,这与gcc(因此也包括gccgo)使用的许可证相同,因此不太可能以任何方式限制使用。请注意,GPL不适用于gojson生成的任何输出;GPL仅适用于包含gojson本身副本的软件。
更多关于golang从JSON自动生成Go结构体定义插件库gojson的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于golang从JSON自动生成Go结构体定义插件库gojson的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
使用gojson从JSON自动生成Go结构体定义
gojson是一个实用的Go语言工具库,可以从JSON数据自动生成对应的Go结构体定义。下面我将详细介绍如何使用这个工具。
安装gojson
首先需要安装gojson工具:
go get -u github.com/ChimeraCoder/gojson/gojson
基本使用
通过命令行使用
假设我们有一个JSON文件data.json:
{
"name": "John Doe",
"age": 30,
"is_active": true,
"address": {
"street": "123 Main St",
"city": "New York"
},
"hobbies": ["reading", "coding", "hiking"]
}
可以通过以下命令生成Go结构体:
cat data.json | gojson -name=Person
输出结果:
type Person struct {
Address struct {
City string `json:"city"`
Street string `json:"street"`
} `json:"address"`
Age int `json:"age"`
Hobbies []string `json:"hobbies"`
IsActive bool `json:"is_active"`
Name string `json:"name"`
}
常用命令行选项
-name=Person
:指定生成的结构体名称-pkg=main
:指定包名-subStruct
:为嵌套结构生成独立类型-forcefloats
:强制使用float64而不是interface{}处理数字
在代码中使用
你也可以在Go代码中直接使用gojson库:
package main
import (
"fmt"
"log"
"github.com/ChimeraCoder/gojson"
)
func main() {
jsonStr := `{
"id": 123,
"title": "Example Post",
"published": true,
"tags": ["tech", "golang"],
"author": {
"name": "Alice",
"email": "alice@example.com"
}
}`
// 生成结构体定义
structDef, err := gojson.Generate(
gojson.ParseJson(jsonStr),
gojson.JsonStruct("Post"),
gojson.SubStruct(true),
)
if err != nil {
log.Fatal(err)
}
fmt.Println(structDef)
}
输出结果:
type Author struct {
Email string `json:"email"`
Name string `json:"name"`
}
type Post struct {
Author Author `json:"author"`
ID int `json:"id"`
Published bool `json:"published"`
Tags []string `json:"tags"`
Title string `json:"title"`
}
高级功能
自定义标签
可以自定义结构体标签:
structDef, err := gojson.Generate(
gojson.ParseJson(jsonStr),
gojson.JsonStruct("Post"),
gojson.FieldTag("json", "bson"),
)
忽略空字段
structDef, err := gojson.Generate(
gojson.ParseJson(jsonStr),
gojson.JsonStruct("Post"),
gojson.OmitEmpty(true),
)
使用指针类型
structDef, err := gojson.Generate(
gojson.ParseJson(jsonStr),
gojson.JsonStruct("Post"),
gojson.UsePointers(true),
)
实际应用示例
假设我们要处理一个API返回的JSON数据:
{
"status": "success",
"data": {
"users": [
{
"id": 1,
"name": "John",
"email": "john@example.com",
"preferences": {
"theme": "dark",
"notifications": true
}
}
],
"total": 1
}
}
使用gojson生成对应的结构体:
cat api_response.json | gojson -name=APIResponse -subStruct -pkg=model
输出:
package model
type Preferences struct {
Notifications bool `json:"notifications"`
Theme string `json:"theme"`
}
type User struct {
Email string `json:"email"`
ID int `json:"id"`
Name string `json:"name"`
Preferences Preferences `json:"preferences"`
}
type Data struct {
Total int `json:"total"`
Users []User `json:"users"`
}
type APIResponse struct {
Data Data `json:"data"`
Status string `json:"status"`
}
注意事项
- 对于不确定类型的字段,gojson会使用
interface{}
类型 - 对于可能为null的字段,建议手动修改为指针类型
- 生成的代码可能需要根据实际需求进行微调
- 对于复杂的JSON结构,可能需要多次调整参数才能得到理想结果
gojson是一个非常有用的工具,可以大大减少手动编写结构体的工作量,特别是在处理复杂JSON API响应时。