Created
March 8, 2018 17:06
-
-
Save s4l1h/cccfebd5c49a14c7ec20a6e49a4aff1a to your computer and use it in GitHub Desktop.
Golang JSON ve interface kullanımı.(v4)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
// Person object | |
type Person struct { | |
FirstName, LastName string // Küçük harf olursa json kütüphanesi erişemeyecek. | |
Number string `json:"number"` // json field name'i değişebiliriz. | |
Company *Company | |
} | |
// MarshalJSON : json kütüphanesi objeye ait MarshalJSON fonksiyonu varsa onu calıştıracak | |
// https://golang.org/pkg/encoding/json/#Marshal | |
func (person *Person) MarshalJSON() ([]byte, error) { | |
return json.Marshal(&struct { // Anonymous bir struct oluşturalım | |
FirstName string `json:"first_name"` | |
LastName string `json:"last_name"` | |
}{ | |
FirstName: person.FirstName, | |
LastName: person.LastName, | |
}) | |
} | |
// Company object | |
type Company struct { | |
Name string `json:"name"` // Şirket Adı | |
Address string // Şirket Adresi | |
Persons []*Person `json:"persons"` // Personeller | |
} | |
// AddPerson to Company | |
func (company *Company) AddPerson(person *Person) { | |
company.Persons = append(company.Persons, person) | |
} | |
func main() { | |
company := &Company{ | |
Name: "AKM", | |
Address: "TeknoKent", | |
} | |
p := &Person{ | |
FirstName: "A.Kadir", | |
LastName: "Mutlu", | |
} | |
p.Number = "0449444944944" | |
p.Company = company // Bu Satırı eklememiz hataya sebep olmuştu. | |
company.AddPerson(p) // Add Person to Company | |
p2 := &Person{ | |
FirstName: "Mujdat", | |
LastName: "Cengiz", | |
} | |
p2.Number = "0449444944944" | |
p2.Company = company // Bu Satırı eklememiz hataya sebep olmuştu. | |
company.AddPerson(p2) // Add Person to Company | |
result, err := json.Marshal(company) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(string(result)) | |
/* | |
{ | |
"name":"AKM", | |
"Address":"TeknoKent", | |
"persons":[ | |
{ | |
"first_name":"A.Kadir", | |
"last_name":"Mutlu" | |
}, | |
{ | |
"first_name":"Mujdat", | |
"last_name":"Cengiz" | |
} | |
] | |
} | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment