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
주의 사항
  • 구조 체 의 개인 필드 (소문 자 필드 는 디 코딩 되 지 않 음)
  • json tag, struct 필드 의 별명
  • json 대상 의 key 는 문자열 이 어야 합 니 다
  • 디 코딩 Unmarshal 이 전달 하 는 필드 는 포인터
  • strust 필드
    type Response struct {Code int json:"code" / code 인 코딩 시 json 에서 code 로 표시 하고 해석 합 니 다. Msg string json:"msg" Data interface {} json:"data" time string / / 개인 필드 는 json 에서 해석 되 지 않 습 니 다. 해석 할 때 이 필드 를 숨 깁 니 다.}
    코딩 Marshal
  • func Marshal(v interface{}) ([]byte, error)
  • func MarshalIndent (v interface {}, prefix, indent string) ([] byte, error) 는 json 문자열 로 인 코딩 되 며, 구조 체 개인 필드 이름 은 인 코딩 되 지 않 습 니 다
  • 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
  • func Unmarshal (data [] byte, v interface {}) error 디 코딩 은 struct 개인 필드 로 json 디 코딩 을 하지 않 습 니 다
  • 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 }

    좋은 웹페이지 즐겨찾기