go get github.com/harlock/goson
package main
import (
"github.com/harlock/goson"
"fmt"
)
type User struct {
Id int
Name string
}
type Comment struct {
Id int
Content string
Author User
}
type Post struct {
Id int
Content string
Author User
Comments []Comment
}
func main() {
post := Post{Id: 1, Content: "blah blah"}
post.Author = User{Id: 1, Name: "User1"}
comment1 := Comment{Id: 1, Content: "Some comment"}
comment1.Author = User{Id:2, Name:"User2"}
comment2 := Comment{Id: 2, Content: "Other comment"}
comment2.Author = User{Id:3, Name:"User3"}
post.Comments = []Comment{comment1, comment2}
// Crete a goson hash, and add the field Id
hash := goson.Hash(post, "Id")
// Add another field
hash.Method("Content")
// Add a hash with the user
hash.Hash("Author", "Id", "Name")
// Add array with comments
comments := hash.Array("Comments", "Id", "Content")
// And add a hash with info about the user
comments.HashAlias("Author", "user", "Id", "Name")
// Print the generated json
json, _ := hash.ToJson()
fmt.Printf("\n%s\n", json)
// Or generate a json array
other_post := Post{Id: 2, Content: "blah blah blah blah"}
other_post.Author = User{Id: 4, Name: "User4"}
other_comment1 := Comment{Id: 3, Content: "Some comment for other post"}
other_comment1.Author = User{Id:5, Name:"User2"}
other_comment2 := Comment{Id: 4, Content: "Other comment for other post"}
other_comment2.Author = User{Id:6, Name:"User6"}
other_post.Comments = []Comment{other_comment1, other_comment2}
// Crete a goson hash, and add the field Id
array := goson.Array([]Post{post, other_post}, "Id")
// Add an alias
array.Alias("text", "Content")
// Add a hash with the user
array.Hash("Author", "Id", "Name")
// Add array alias
array.ArrayAlias("Comments", "com", "Id", "Content").HashAlias("Author", "user", "Id", "Name")
// Print the generated json
json, _ = array.ToJson()
fmt.Printf("\n%s\n", json)
}
This will generate
{
"author": {
"id": 1,
"name": "User1"
},
"comments": [
{
"content": "Some comment",
"id": 1,
"user": {
"id": 2,
"name": "User2"
}
},
{
"content": "Other comment",
"id": 2,
"user": {
"id": 3,
"name": "User3"
}
}
],
"content": "blah blah",
"id": 1
}
And
[
{
"author": {
"id": 1,
"name": "User1"
},
"com": [
{
"content": "Some comment",
"id": 1,
"user": {
"id": 2,
"name": "User2"
}
},
{
"content": "Other comment",
"id": 2,
"user": {
"id": 3,
"name": "User3"
}
}
],
"id": 1,
"text": "blah blah"
},
{
"author": {
"id": 4,
"name": "User4"
},
"com": [
{
"content": "Some comment for other post",
"id": 3,
"user": {
"id": 5,
"name": "User2"
}
},
{
"content": "Other comment for other post",
"id": 4,
"user": {
"id": 6,
"name": "User6"
}
}
],
"id": 2,
"text": "blah blah blah blah"
}
]