JSON serialization of Golang

Source: Internet
Author: User
Tags switch case

JSON is a simple data interchange format, syntax-like JavaScript objects and lists, is the most common back-end and run on the Web page between JS Communication format.

Encoding

Encoding JSON data requires the use of the marshal () function.

Func Marshal (vInterface{}) ([]byte, error) type Messagestruct{NamestringBodystringTime int64}m:= message{"Alice","Hello",1294706395881547000}b, err:=JSON. Marshal (m) b== []byte(`{"Name":"Alice","Body":"Hello"," Time":1294706395881547000}`)

The code above is about a Message object encoded in JSON format. The display in JSON format is []byte type.

Decoding:

The Unmarshal () function is used to decode data in JSON format.

Func unmarshal (data []byteinterface{}) Errorvar  m Messageerr:= json. Unmarshal (b, &m)

Unmarshal () accepts the JSON data of the []byte type, and the pointer of the struct to which the data is to be returned.

In the Unmarshal () function. Only attribute fields that are owned by M in this struct are recognized. Non-existent will be ignored.

Generic JSON interface: interface{}

Any go type implements an empty interface interface{}

var Interface  "a string"2.777

An assertion can be used to determine its implementation type

R: = I. (float64) FMT. Println ("thecircle ' sarea", Math.) PI*R*R)

If you do not know the type of implementation, you can use the Swtich case to determine

SwitchV: =i. (type) { Case int: FMT. Println ("twice I is", v*2) Casefloat64:fmt. Println ("The reciprocal of I is",1/v) Case string: H:= Len (v)/2FMT. Println ("I swapped by halves", v[h:]+V[:h])default:    //i isn ' t one of the types above}

The JSON package uses map[string]interface{} and []interface{} to store any JSON objects and arrays. The type of go and the type of JSON correspond to the following:

    • boolFor JSON Booleans,
    • float64For JSON numbers,
    • stringFor JSON strings,
    • nilFor JSON null.
Decode arbitrary data

Suppose the book JSON data stored in B

B: = []byte(' {"Name":"Wednesday","  Age":6,"parents": ["Gomez" ,"morticia"]} ')

When you do not know the structure of this data, you can use Unmarshal () to decode it into a value of interface{}.

var Interface {}err:= json. Unmarshal (b, &f)

f The current data structure is a map[string]interface{}

f = map[string]Interface{}{    "Name":"Wednesday",    " Age":6,    "Parents": []Interface{}{        "Gomez",        "Morticia",    },}

You can use the underlying interface of assertion F to access this data

M: = f. (map[string]interface{})

Then traverse the map and use the switch case to assert the underlying type

 forK, V: =Range M {SwitchVV: =v. (type) { Case string: FMT. Println (k,"is string", VV) Case int: FMT. Println (k,"is int", VV) Case[]Interface{}: FMT. Println (k,"is an array:")         forI, U: =range VV {fmt. Println (I, u)}default: FMT. Println (k,"is of a type I don ' t know what to handle")    }}
Reference Types:
struct {    Name        string     ageint    parents [ ]  String}    var  m Familymember    err:= json. Unmarshal (b, &m)

Encode the []byte data in B] into the familymember structure,

Let's define a Go type to contain the data from the previous example:

Type familymember struct {    Name    string    age     int    parents []string}    var m familymember    Err: = json. Unmarshal (b, &m)

Unmarshaling that data to a FamilyMember value works as expected, but if we look closely we can see a remarkable thing have Happ Ened. With the Var statement we allocated a FamilyMember struct, and then provided a pointer Unmarshal to that value to, but at that time th E Parents field was a nil slice value. Parentsto populate the field, Unmarshal allocated a new slice behind the scenes. This was typical of how Unmarshal works with the supported reference types (pointers, slices, and maps).

Consider unmarshaling into this data structure:

Type Foo struct {    Bar *bar}

If There were a Bar field in the JSON object, Unmarshal would allocate a new and Bar populate it. If not, would is left as Bar a nil pointer.

From this a useful pattern arises:if you has an application that receives a few distinct message types, you might define "Receiver" structure like

Type incomingmessage struct {    Cmd *command    Msg *message}

And the sending party can populate Cmd the field and/or Msg the field of the top-level JSON object, depending on the T Ype of message they want to communicate. When Unmarshal decoding IncomingMessage the JSON to an struct, would only allocate the data structures present in the JSON data. To know which messages to process, the programmer need simply test that either Cmd or was not Msg nil .

Streaming encoders and decoders

The JSON package provides and types to the Decoder Encoder common operation of reading and writing streams of JSON dat A. The and NewDecoder NewEncoder functions wrap the and io.Reader io.Writer interface types.

Func newdecoder (R io. Reader) *decoderfunc newencoder (w io. Writer) *encoder

Here's a example program that reads a series of JSON objects from standard input, removes all, and the Name field from EA Ch object, and then writes the objects to standard output:

Package Mainimport (    "Encoding/json"    "Log" "    OS") Func main () {    Dec: = json. Newdecoder (OS. Stdin)    ENC: = json. Newencoder (OS. Stdout) for    {        var v map[string]interface{}        If err: = Dec. Decode (&V); Err! = Nil {            log.  PRINTLN (Err)            return        } for        k: = Range v {            if k! = "Name" {                Delete (V, k)}        }        If err : = Enc. Encode (&V); Err! = Nil {            log. PRINTLN (Err)        }}}    

Due to the ubiquity of Readers and writers, these Encoder and Decoder types can is used in a broad range of scenarios, such as Reading and writing to HTTP connections, WebSockets, or files.

JSON serialization of Golang

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.