When we use Golang json to marshal a struct, the non-exported members of the struct will not be able to be accessed by JSON, that is, the result of JSON encoding will not appear (that is, lowercase members cannot export).
This is due to a technical problem: the name of the member in the Golang struct is not accessible if it starts with a lowercase letter, that is, JSON cannot access the member that begins with the lowercase letter in our struct
This can be solved in two ways.
1. The members of the struct start with uppercase, then add tag
2. Implement JSON. Marshaler interface
The first method is more common.
The second method is as follows
Http://play.golang.org/p/AiTwUOWkiT
Package Mainimport "FMT" import "Encoding/json" Func Main () {var s ss.a = 5s.b[0] = 3.123s.b[1] = 111.11s.b[2] = 1234.123s.c = "Hello" s.d[0] = 0x55j, _: = json. Marshal (s) fmt. Println (String (j))}type S struct {a intb [4]float32c stringd [12]byte}func (This S) Marshaljson () ([]byte, error) {return Json. Marshal (map[string]interface{}{"a": This.a, "B": this.b, "C": THIS.C, "D": THIS.D,})}
Output:
{"A": 5, "B": [3.123,111.11,1234.123,0], "C": "Hello", "D": [85,0,0,0,0,0,0,0,0,0,0,0]}
That is, the struct implements the Marshaljson () ([]byte, error) function, and in this function you export the members you want to export.
This makes it possible to use JSON as normal. A function like Marshal.