1. json과 go간 타입 맵핑
JSON | Go |
Boolean | bool |
Number | float64 |
String | string |
Array | []interface{} |
Object | map[string]interface{} |
Null | nil |
2. 예제코드
package main
import (
"encoding/json"
"fmt"
"log"
)
type Person struct {
Name string
Age int
Hobbies []string
}
func main() {
hobbies := []string{"book", "execise", "running"}
p := Person{
Name: "test",
Age: 10,
Hobbies: hobbies,
}
fmt.Printf("%+v\n", p)
jsonByteData, err := json.Marshal(p)
if err != nil {
log.Fatal(err)
}
jsonStringData := string(jsonByteData)
fmt.Println(jsonStringData)
}
================================================
type Person struct {
Name string `json:"name,omitempty"` // json값을 empty로
Age int `json:"age,omitempty"`
Hobbies []string `json:"hobbies,omitempty"`
}
================================================
package main
import (
"encoding/json"
"fmt"
"log"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Hobbies []string `json:"hobbies"`
}
func main() {
jsonStringData := `{"name":"test","age":10,"hobbies":["book", "execise", "running"]}`
jsonByteData := []byte(jsonStringData)
p := Person{}
err := json.Unmarshal(jsonByteData, &p)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", p)
}
================================================
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type User struct {
Name string `json:"name"`
Blog string `json:"blog"`
}
func main() {
var u User
res, err := http.Get("https://api.github.com/users/khkwon01")
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(&u)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", u)
}
================================================
package main
import (
"encoding/json"
"fmt"
"log"
)
type Switch struct {
On bool `json:"on"`
}
func main() {
jsonStringData := `{"on":"true"}`
jsonByteData := []byte(jsonStringData)
s := Switch{}
err := json.Unmarshal(jsonByteData, &s)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", s)
}
'Language > go' 카테고리의 다른 글
protocol buffer (0) | 2019.05.09 |
---|---|
regexp 코드 (0) | 2018.03.15 |
http client 코드 (0) | 2018.03.15 |
http 서버 코드 (0) | 2018.03.15 |
goroutine 기본 구조 (0) | 2018.01.02 |