This article has participated in the weekend study program, click to see more details
This is the second day of my participation in Gwen Challenge
Commonly used method
Marshal method introduction
func Marshal(v interface{}) ([]byte, error)
Copy the code
This method iterates over V recursively, and by default, it deserializes and deserializes data according to the following correspondence.
- Boolean – JSON booleans
- Float point, INTEGER, number — JSON numbers
- String — JSON strings (will be forcibly encoded to UTF-8, so it is safe to embed them in HTML. For example, “<” will be replaced with “\u003c”, not when SetEscapeHTML(false) is set.)
- Array, Slice — JSON Arrays
- Struct – JSON objects
Initialization of a structure is a bit special, and we’ll look at it in more detail.
Field int 'json:"myName"' // myName is still the key, but because of the omitEmpty keyword, when the Field value is empty, Field int 'json:"myName, omitEmpty "' // Will skip this Field if the value is empty, since no key is specified, Field int 'json:",omitempty"' // This Field will be ignored. Field int 'json:"-"' // Note that this is not the same as above. Field name is -field int 'json:"-,"'Copy the code
There’s another way to write it. Fields are stored as JSON in jSON-encoded strings. It applies only to strings, floating point, integer, or Boolean fields. This additional encoding level is sometimes used when communicating with JavaScript programs.
Int64String int64 `json:",string"`
Copy the code
- Map — JSON Objects (Note that map keys must be of comparable types, but this is golang’s knowledge)
- Pointer – The value of this pointer
- Channels and functions cannot be encoded.
One quick question: Can JSON handle looping data structures? Take a look at the first sentence introduction to this method.
Write a small example and try it out
type Xiaowu struct { Age float32 `json:"aGe"` Color string `json:"color,omitempty"` character Com `json:"character"` } type Com struct { Lovely bool `json:"lovely,omitempty"` Cute bool `json:"cute,omitempty"` Naughty string `json:"-"` } Func main() {Miao := Xiaowu{Age: 0.5, Color: "grey", character: Com{Lovely: true, Naughty: "true", }, } lovelyMiao,_ := json.Marshal(miao) log.Println("miao :",string(lovelyMiao)) }Copy the code
The output is:
Miao: {" aGe ": 0.5," color ":" grey "}Copy the code
Uh-oh, that doesn’t seem to meet expectations. Emm… You can see that the fields that are not printed are lowercase and cannot be encoded. The output after modification is
Miao: {" aGe ": 0.5," color ":" grey "and" character ": {" lovely" : true}}Copy the code
Well, that’s all for today. It’s good to learn a little bit each day and rest early 🙂 check out Unmarshal tomorrow.