golang入門–json形のデータを操作するサンプルコード
サンプルコード
package main
import (
“fmt"
“encoding/json"
)
type User struct {
Username string
Password string
FriendName []string
}
func main() {
user:=User{}
user.Username="Tamura"
user.Password="pwd3456″
user.FriendName=[]string{“Suzuki","kaoli"}
//struct->json
if userJSON,err:=json.Marshal(user);err==nil{
fmt.Println(string(userJSON))
}
//slice->json
arr:=[]string{“Apple","Orange","Banana"}
if arrJSON,err:=json.Marshal(arr);err==nil{
fmt.Println(string(arrJSON))
}
//map->json
m:=map[string]string{“東京都":"品川区","埼玉県":"西川口"}
if mJSON,err:=json.Marshal(m);err==nil{
fmt.Println(string(mJSON))
}
//json->struct
jsonStr:='{“Username":"Tamura","Password":"pwd3456″,"FriendName":[“Suzuki","kaoli"]}’
var userJSON User
if err:=json.Unmarshal([]byte(jsonStr),&userJSON);err==nil{
fmt.Println(userJSON)
}
//json->slice
jsonFruit:='[“Apple","Orange","Banana"]’
var arrFruit []string
if err:=json.Unmarshal([]byte(jsonFruit),&arrFruit);err==nil{
fmt.Println(arrFruit)
}
//json->map
jsonCity:='{“東京都":"品川区","埼玉県":"西川口"}’
var mapCity map[string]string
if err:=json.Unmarshal([]byte(jsonCity),&mapCity);err==nil{
fmt.Println(mapCity)
}
}