golang? json processing

 

Serialization:

 1) simple data structure:

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

type School struct {
    Name     string        `json:"name"`
    Location string     `json:"location"`
}

func main()  {
    school := School{
        The Name:      " a certain school " ,
        LOCATION: " urban " ,
    }

    str, err := json.Marshal(school)

    if err !=nil {
        fmt.Printf ( " JSON serialization failure V% " , ERR)
    }

    fmt.Println (STR)     // return the result [1,233,411,097,109,101 34 is 5,834,230,159,144,230,159 144,229,173,166,230 160,161,344,434,108 1,119,997,116,105,111,110 345,834,229,184,130 229 34 is 125 186 140] 
    fmt.Println (reflect.TypeOf (STR))     // returns the result [] uint8 
    fmt.Println ( String (STR))     // return the result { "name": "a certain school", "location" : "downtown"} 
}

Explain Why go through the last demo convert a string to print out the final result: final result json.Marshal return is the result of type byte slice, byte and string can be converted to each other.

 

2) nested structure:  

package main

import (
    "encoding/json"
    "fmt"
)

type Classroom struct {
    Number int64    `json:"number"`
    Floor  int32    `json:"floor"`
}

type School struct {
    Name     string        `json:"name"`
    Location string     `json:"location"`
    Classroom Classroom `json:"classroom"`
}

func main()  {
    school := School{
        The Name:       " a certain school " ,
        LOCATION:   " urban " ,
        Classroom:Classroom{
            Number: 201,
            Floor:  2,
        },
    }

    str, err := json.Marshal(school)

    if err !=nil {
        fmt.Printf ( " JSON serialization failure V% " , ERR)
    }

    fmt.Println ( String (STR))     // return the result { "name": "a certain school", "location": "urban", "classroom": { " number": 201, "floor": 2} } 
}

school classroom of a nested structure, can be initialized after the assignment of the direct sequence.

 

3) definition of the structure is not the practice of:

package main

import (
    "encoding/json"
    "fmt"
)

func main()  {
    school := map[string]interface{}{
        "name" : "某某学校",
        "location" : "市区",
        "classroom" : map[string]interface{}{
            "number" : 201,
            "floor" : 2,
        },
    }

    str, err := json.Marshal(school)

    if err !=nil {
        fmt.Printf ( " JSON serialization failure V% " , ERR)
    }

    fmt.Println ( String (STR))     // return the result { "name": "a certain school", "location": "urban", "classroom": { " number": 201, "floor": 2} } 
}

After initialization can assign serialized directly.

 

Deserialization

1) simple structure:

package main

import (
    "encoding/json"
    "fmt"
)

type Classroom struct {
    Number int64    `json:"number"`
    Floor  int32    `json:"floor"`
}

type School struct {
    Name     string        `json:"name"`
    Location string     `json:"location"`
    Classroom Classroom `json:"classroom"`
}

func main()  {
    str := `{"name":"某某学校","location":"市区","classroom":{"number":201,"floor":2}}`
    var school School
    json.Unmarshal ([] byte (STR), & School)     // FUNC Unmarshal (Data [] byte, interface {V}) {error 
    fmt.Println (School)     // return the result {certain urban school {2012} } 
    fmt.Printf ( `name:% S, LOCATION:% S, Classroom:% V, Number: D%, Floor:% d`,
        school.Name, school.Location, school.Classroom, school.Classroom.Number, school.Classroom.Floor)    //name:某某学校, location:市区, classroom:{201 2}, number:201, floor:2
}

Unmarshal pass pass a required value of the first byte of the last slice types can not directly pass str, str, and the type byte can be transformed into each other. Examples of the results of the previous sequence of the time is the return of byte type, it is converted into our own str of.

Parameters need to pass a second structure pointer in the past, if the direct transmission value, the sequence of the copy is not the final result.

 

2) Direct deserialization

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func main()  {
    str := `{"name":"某某学校","location":"市区","classroom":{"number":201,"floor":2}}`
    var school interface{}
    json.Unmarshal ([] byte (STR), & School)     // FUNC Unmarshal (Data [] byte, interface {V}) {error 
    fmt.Println (School)     // returns the result map [classroom: map [floor: 2 number : 201] location: urban name: certain schools]
     // fmt.Println (school.name)     // compiler error undefined school.name (of the type interface {} interface with IS NO Methods)
     // fmt.Println (school [ "name"])     // compiler error Operation invalid: School [ "name"] ({} type interface does Not Support Indexing) 

    Val, OK: = School (Map [. String ] interface {})

    if !ok {
        fmt.Println("type is not ok")
        return
    }

    fmt.Println (Val [ " name " ])     // return the result certain school 
    fmt.Println (Val [ " Classroom " ])     // returns the result map [floor: 2 number: 201 ]

    //fmt.Println(val["classroom"]["number"])    //编译报错  invalid operation: val["classroom"]["number"] (type interface {} does not support indexing)

    classroom, ok := val["classroom"].(map[string]interface{})

    if !ok {
        fmt.Println("type is not ok")
        return
    }

    fmt.Println (Classroom [ " Number " ])     // return result 201 
    fmt.Println (reflect.TypeOf (Classroom [ " Number " ]))     // return the result float64 
}

If you do not want to define a data structure, you can define an empty interface directly deserialized, but after unserialized value will be compile-time error, so the first assertion about the map types.

 

Guess you like

Origin www.cnblogs.com/smallbo/p/12318282.html