Skip to content

Instantly share code, notes, and snippets.

@AlexMocioi
Created April 6, 2014 16:21
Show Gist options
  • Save AlexMocioi/10008253 to your computer and use it in GitHub Desktop.
Save AlexMocioi/10008253 to your computer and use it in GitHub Desktop.
Map json to struct in GO, for direct marshal, unmarshal
package main
import "encoding/json"
import "fmt"
type Person struct {
Name string `json:"name"`
Age int `json:"age,omitempty"`
Addr *Address `json:"address,omitempty"`
Ph []string `json:"phone,omitempty"`
}
//Astea-s faine aici ca imi definesc corespondenta, si cand fac unmarshall,
//merge blana, plus ca am si validarile alea, p-asta da-l deoparte daca e empty,
//ca nu ma intereseaza.
type Address struct {
Street string `json:"street"`
City string `json:"city"`
State string `json:"state"`
Zip string `json:"zip"`
}
func main() {
// compare with output, note apt field ignored, missing fields
// have zero values.
jData := []byte(`{
"name": "Smith",
"address": {
"street": "21 2nd Street",
"apt": "507",
"city": "New York",
"state": "NY",
"zip": "10021"
}
}`)
var p Person
err := json.Unmarshal(jData, &p)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%+v\n %+v\n\n", p, p.Addr)
}
// compare with output, note empty fields omitted.
pList := []Person{
{
Name: "Jones",
Age: 21,
},
{
Name: "Smith",
Addr: &Address{"21 2nd Street", "New York", "NY", "10021"},
Ph: []string{"212 555-1234", "646 555-4567"},
},
}
jData, err = json.MarshalIndent(pList, "", " ")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(jData))
}
}
/*
Output:
{Name:Smith Age:0 Addr:0xf840026080 Ph:[]}
&{Street:21 2nd Street City:New York State:NY Zip:10021}
[
{
"name": "Jones",
"age": 21
},
{
"name": "Smith",
"address": {
"street": "21 2nd Street",
"city": "New York",
"state": "NY",
"zip": "10021"
},
"phone": [
"212 555-1234",
"646 555-4567"
]
}
]
*/
//Noi avem impachetarea json-ului facuta at labam, in multe locuri, si ar merge pe varianta asta,
//sa imi definesc corespondenta. Imi fac o structura mare, care este comuna tuturor response-urilor,
//si detaliile le lipesc de mana. Nu peste tot, ca de multe ori sunt proxy, si dau exact cum primesc
//dinspre client spre couch si invers, dar unde fac procesare, cred ca ar fi mai eleganta varianta asta,
//decat ce facem noi cu map-uri si impachetare json de mana. Ce ziceti?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment