Golang converting a struct into a json,json to a struct
Last Update:2018-08-23
Source: Internet
Author: User
1. The MARSHL function (or marshlindent () function) is required to convert the struct to JSON. Difference: The MARSHL function does not format the JSON output, and the output is a JSON string. ----is not conducive to directly viewing the structure of JSON. The Maeshldent function can format the JSON output, which improves readability. 2. The MARSHL () function is required to convert a JSON string into a struct. Examples are as follows: "' Gopackage mainimport (" Log "" Encoding/json "" FMT ") type Movie struct{Title string year int ' JSON:" released "' Colo r BOOL ' JSON: ' Color, omitempty ' Actors []string}func main () {var movies = []movie{{Title: ' Casabanca ', year:1942, color: False, actors:[]string{"Humphrey Bogart", "Ingrid Bergman"}}, {Title: "CASABANCA2", year:1962, Color:true, actors:[] string{"Humphrey Paul"}}, data, err: = json. Marshal (Movies) if err! = Nil {log. Fatalf ("Json marshaling failed:%s", err)} FMT. Printf ("%s\n", data) var movies2 []struct{title String}//Movies2: = Make ([]movie, ten) if ERR3: = json. Unmarshal (data, &movies2); ERR3!=nil{Log. Fatalf ("JSON unmarshling failed:%s", err)} FMT. Println ("*****************", Movies2) data2, ERR2: = json. Marshalindent (Movies, "", "") if err2! = Nil {log. Fatalf ("Json marshlindent failed:%S ", err)} FMT. Printf ("%s\n", data2)}//2package mainimport ("Log" "Encoding/json" "FMT") type Movie struct{Title string year int ' JSON: "Released" ' Color bool ' JSON: "Color, Omitempty" ' Actors []string}func main () {var movies = []movie{{Title: "Casabanca", Ye ar:1942, Color:false, actors:[]string{"Humphrey Bogart", "Ingrid Bergman"}}, {Title: "CASABANCA2", year:1962, Color: True, actors:[]string{"Humphrey Paul"}}, data, err: = json. Marshal (Movies) if err! = Nil {log. Fatalf ("Json marshaling failed:%s", err)} FMT. Printf ("%s\n", data) var movies2 []struct{title String}//Movies2: = Make ([]movie, ten) if ERR3: = json. Unmarshal (data, &movies2); ERR3!=nil{Log. Fatalf ("JSON unmarshling failed:%s", err)} FMT. Println ("*****************", Movies2) data2, ERR2: = json. Marshalindent (Movies, "", "") if err2! = Nil {log. Fatalf ("Json marshlindent failed:%s", err)} FMT. Printf ("%s\n", Data2)} "133 reads