// Given a tag string with the format specified in the package comment, // parseFieldParameters will parse it into a fieldParameters structure, // ignoring unknown parts of the string. funcparseFieldParameters(str string) (ret fieldParameters) { var part string forlen(str) > 0 { // This loop uses IndexByte and explicit slicing // instead of strings.Split(str, ",") to reduce allocations. i := strings.IndexByte(str, ',') if i < 0 { part, str = str, "" } else { part, str = str[:i], str[i+1:] } switch { case part == "optional": ret.optional = true case part == "explicit": ret.explicit = true if ret.tag == nil { ret.tag = new(int) } case part == "generalized": ret.timeType = TagGeneralizedTime case part == "utc": ret.timeType = TagUTCTime case part == "ia5": ret.stringType = TagIA5String case part == "printable": ret.stringType = TagPrintableString case part == "numeric": ret.stringType = TagNumericString case part == "utf8": ret.stringType = TagUTF8String case strings.HasPrefix(part, "default:"): i, err := strconv.ParseInt(part[8:], 10, 64) if err == nil { ret.defaultValue = new(int64) *ret.defaultValue = i } case strings.HasPrefix(part, "tag:"): i, err := strconv.Atoi(part[4:]) if err == nil { ret.tag = new(int) *ret.tag = i } case part == "set": ret.set = true case part == "application": ret.application = true if ret.tag == nil { ret.tag = new(int) } case part == "private": ret.private = true if ret.tag == nil { ret.tag = new(int) } case part == "omitempty": ret.omitEmpty = true } } return }
type User struct { ID int64`json:"id"` Name string`json:"string"` Gender string`json:"gender,omitempty"` //Address *address `json:"address,omitempty"` Address json.RawMessage `json:"address,omitempty"` }
type address struct { Country string`json:"country"` Province string`json:"province"` City string`json:"accessKey"` Street string`json:"street"` }
funcmain() {
s := User{ 15, "XiaoMing", "", nil, } sJson, err := json.Marshal(s) if err != nil { fmt.Println(err) return } fmt.Println("json of s = ", string(sJson))
type User struct { ID int64`json:"id"` Name string`json:"string"` Gender string`json:"gender,omitempty"` //Address *address `json:"address,omitempty"` //Address json.RawMessage `json:"address,omitempty"` Address interface{} `json:"address,omitempty"` }
type address struct { Country string`json:"country"` Province string`json:"province"` City string`json:"accessKey"` Street string`json:"street"` }
funcmain() {
s := User{ 15, "XiaoMing", "", nil, } sJson, err := json.Marshal(s) if err != nil { fmt.Println(err) return } fmt.Println("json of s = ", string(sJson))