Using JSON in Golang

Source: Internet
Author: User

Some examples of using JSON in Golang

Go_json_test Project Main.gopackage mainimport ("Encoding/json" "FMT") func encode_from_map_test () {fmt. Printf ("encode_from_map_test\n") m: = map[string][]string{"level": {"Debug"}, "message": {"File not fo und "," Stack Overflow "},} if data, err: = json. Marshal (m); Err = = Nil {fmt. Printf ("%s\n", data)}}type gameinfo struct {game_id int64 game_map string game_time int32}func Encode_fro M_object_test () {fmt. Printf ("encode_from_object_test\n") Game_infos: = []gameinfo{gameinfo{1, "Map1", +}, gameinfo{2, "MAP2" , $},} if data, err: = json. Marshal (Game_infos); Err = = Nil {fmt.    Printf ("%s\n", data)}}type GameInfo1 struct {game_id int64 ' JSON: "game_id" '//game_id resolves to game_id  Game_map string ' JSON: ' game_map,omitempty '///gamemap resolves to game_map, ignoring empty game_time int32 game_name string ' json: '-' ' Ignore Game_name}func encode_from_object_tag_test () {fmt. Printf ("Encode_frOm_object_tag_test\n ") Game_infos: = []gameinfo1{gameinfo1{1," Map1 "," name1 "}, Gameinfo1{2," Map2 ", "Name2"}, Gameinfo1{3, "", "Name3"},} if data, err: = json. Marshal (Game_infos); Err = = Nil {fmt. Printf ("%s\n", data)}}type baseobject struct {field_a string field_b string}type deriveobject struct {baseo Bject Field_c String}func Encode_from_object_with_anonymous_field () {fmt. Printf ("encode_from_object_with_anonymous_field\n") object: = deriveobject{baseobject{"A", "B"}, "C"} if data, err: = json. Marshal (object); Err = = Nil {fmt. Printf ("%s\n", data)}}//convert interface//when calling Marshal (v interface{}), the function will determine whether v satisfies the JSON. Marshaler or encoding. Marshaler interface,//If satisfied, the two interfaces are called for conversion (if two are satisfied, the JSON is called first. Marshaler)/*//JSON. Marshalertype Marshaler Interface {Marshaljson () ([]byte, error)}//encoding.    Textmarshalertype Textmarshaler Interface {marshaltext () (text []byte, err Error)}*/type point struct {X int Y Int}func (pt Point) Marshaljson ([]byte, error) {return []byte (FMT). Sprintf (' {' px ':%d, ' py ':%d} ', Pt. X, Pt. Y)), Nil}func Encode_from_object_with_marshaler_interface () {fmt. Printf ("encode_from_object_with_marshaler_interface\n") if data, err: = json. Marshal (POINT{50, 50}); Err = = Nil {fmt. Printf ("%s\n", data)} else {fmt. Printf ("Error%s\n", err.) Error ())}}type Point1 struct {X int Y int}func (pt Point1) Marshaltext () ([]byte, error) {return []byte (FMT . Sprintf (' {' px ':%d, ' py ':%d} ', Pt. X, Pt. Y)), Nil}func Encode_from_object_with_text_marshaler_interface () {fmt. Printf ("encode_from_object_with_text_marshaler_interface\n") if data, err: = json. Marshal (POINT1{50, 50}); Err = = Nil {fmt. Printf ("%s\n", data)} else {fmt. Printf ("Error%s\n", err.) Error ())}}//decode TestFunc decode_to_map_test () {fmt. Printf ("decode_to_map_test\n") Data: = ' [{' Level ': ' Debug ', ' MSG ': ' File: \ ' test.txt\ ' not Found '}, '+ ' {"Level": "", "MSG": "Logic Error"}] ' var Debug_infos []map[string]string JSON. Unmarshal ([]byte (data), &debug_infos) fmt. Println (Debug_infos)}type debuginfo struct {level string MSG string Author string//non-exported field is not parsed by JSON}func (db Ginfo debuginfo) string () string {return FMT. Sprintf ("{level:%s, MSG:%s}", Dbginfo.level, dbginfo.msg)}func decode_to_object_test () {fmt. Printf ("decode_to_object_test\n") Data: = ' [{"Level]:" Debug "," MSG ":" File not Found "," Author ":" Cynhard "}, ' + ' {" L Evel ":" "," MSG ":" Logic Error "," Author ":" Gopher "}] ' var Dbginfos []debuginfo JSON. Unmarshal ([]byte (data), &dbginfos) fmt. Println (Dbginfos)}type debuginfotag struct {level string ' JSON: ' Level '//level decoded to level MSG string ' JSON: '    Message "//message decoded to MSG Author string ' JSON:"-"'///Ignore Author}func (Dbginfo Debuginfotag) string () string { Return to FMT. Sprintf ("{level:%s, MSG:%s}", Dbginfo.level, dbginfo.msg)}func Decode_to_objeCt_tag_test () {fmt.        Printf ("decode_to_object_tag_test\n") Data: = ' [{' Level ': ' Debug ', ' Message ': ' File not Found ', ' Author ': ' Cynhard '}, ' + ' {' Level ': ', ' message ': ' Logic error ', ' Author ': ' Gopher '}] ' var Dbginfos []debuginfotag JSON. Unmarshal ([]byte (data), &dbginfos) fmt. Println (Dbginfos)}type pointx struct{X, Y int}type Circle struct {pointx Radius int}func (c Circle) String () stri ng {return FMT. Sprintf ("{point{x:%d, Y:%d}, Radius:%d}", c.pointx.x, C.pointx.y, C.radius)}func decode_to_object_with_anonymous _field () {fmt. Printf ("decode_to_object_with_anonymous_field\n") Data: = ' {' X ': +, ' Y ': $, ' Radius ': +} ' var c Circle json. Unmarshal ([]byte (data), &c) fmt. Println (c)}//decode convert interface//decoding when the JSON is satisfied according to the parameters. Unmarshaler and Encoding.textunmarshaler call the corresponding function (if two functions are present, priority call Unmarshaljson)/*//JSON. Unmarshalertype Unmarshaler Interface {Unmarshaljson ([]byte) error}//encoding.    Textunmarshalertype Textunmarshaler Interface {Unmarshaltext (text []byte) error}*/type pointy struct{X, Y int}func (PT pointy) Marshaljson () ([]byte, error) {//No Decode, just print return []byte (FMT. Sprintf (' {' X ':%d, ' Y ':%d} ', Pt. X, Pt. Y)), Nil}func Decode_to_object_with_marshaler_interface () {fmt. Printf ("decode_to_object_with_marshaler_interface\n") if data, err: = json. Marshal (POINTY{50, 50}); Err = = Nil {fmt. Printf ("%s\n", data)}}func main () {FMT.    Println ("JSON test!") Fmt. Printf ("Ecode test\n") encode_from_map_test () encode_from_object_test () encode_from_object_tag_test () Encode_f Rom_object_with_anonymous_field () encode_from_object_with_marshaler_interface () Encode_from_object_with_text_ Marshaler_interface () fmt. Printf ("Decode test\n") decode_to_map_test () decode_to_object_test () decode_to_object_tag_test () decode_to_obj Ect_with_anonymous_field () Decode_to_object_with_marshaler_interface ()}

Run Result:

JSON Test!ecode testencode_from_map_test{"level": ["Debug"], "message": ["File not Found", "Stack Overflow"]}encode_ from_object_test[{"game_id": 1, "Game_map": "Map1", "Game_time": 20},{"game_id": 2, "Game_map": "Map2", "Game_time": 60} ]encode_from_object_tag_test[{"game_id": 1, "Game_map": "Map1", "Game_time": 20},{"game_id": 2, "Game_map": "Map2", " Game_time ": 60},{" game_id ": 3," Game_time ": 120}]encode_from_object_with_anonymous_field{" Field_a ":" A "," Field_b ":" B "," Field_c ":" C "}encode_from_object_with_marshaler_interface{" px ":" py ": 50}encode_from_object_with_text_ Marshaler_interface "{\" px\ ":", \ "py\": "Decode Testdecode_to_map_test[map[level:debug msg:file:" Test.txt "not Found] Map[level:msg:logic error]]decode_to_object_test[{level:debug, msg:file not Found} {level:, Msg:logic error}]d Ecode_to_object_tag_test[{level:debug, Msg:file not Found} {level:, Msg:logic error}]decode_to_object_with_anonymous _FIELD{POINT{X:80, y:80}, radius:40}decode_to_object_with_marshaler_interface{"X": +, "Y": 50} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.