go 에서 json 상용 동작
4294 단어 go.
공식 소개:http://golang.org/doc/articles/json_and_go.html
대조 관계
go
json
bool
booleans
float64
numbers
string
strings
[]interface{}
array
map[string]interface{}
objects
nil
null
주의 사항
type Response struct {Code int
json:"code"
/ code 인 코딩 시 json 에서 code 로 표시 하고 해석 합 니 다. Msg string json:"msg"
Data interface {} json:"data"
time string / / 개인 필드 는 json 에서 해석 되 지 않 습 니 다. 해석 할 때 이 필드 를 숨 깁 니 다.}코딩 Marshal
type Response struct {
Code int `json:"code"` // json tag,
Msg string `json:"msg"`
Data interface{} `json:"data"`
time string // json
}
func main() {
resp := Response{Code: 9999, Msg: " ", Data: "bings",time:"1996"}
if data, err := json.Marshal(resp); err == nil {
fmt.Printf("%s", data)
}
}
:{"code":9999,"msg":" ","data":"bings"}
출력 내용 이 길 어 읽 기 가 쉽 지 않 으 면 방법 2 를 사용 하여 출력 포맷 할 수 있 습 니 다.
if data, err := json.MarshalIndent(resp,"","\t"); err == nil {
fmt.Printf("%s", data)
}
{
"code": 9999,
"msg": " ",
"data": "bings"
}
Unmarshal
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
time string // json
}
func main() {
jsonString := "{\"code\":9999,\"msg\":\" \",\"data\":\"bings\",\"time\":\"1997\"}"
var resp Response
err := json.Unmarshal([]byte(jsonString), &resp)
if err == nil {
fmt.Println(resp)
}
}
{9999 bings }