XMLJSONJSONGojsonJSON
JSON
JSON
func Unmarshal(data []byte, v interface{}) error

通过这个例子可以实现解析的目的,具体实例如下:

type Server struct {
    serverName string
    serverIP string
}

type Serverslice struct {
    Servers []Server
}

func main() {
    var s Serverslice
    str := `{"servers":[{"serverName":"Local_Web","serverIP":"127.0.0.1"},{"serverName":"Local_DB","serverIP":"127.0.0.2"}]}`
    json.Unmarshal([]byte(str), &s)
    fmt.Println(s)
}
JSONsliceJSONKEYJSONstruct
tagKEYstructKEYKEY
interface{}JSONjsonmap[string]interface{}[]interface{}JSONJSONJSONBitlysimplejsonJSON
package main

import (
    "fmt"
    "github.com/bitly/go-simplejson"
    "os"
)

func main() {
    js, err := simplejson.NewJson([]byte(`{
        "test": {
                "array": [1, "2", 3],
                "int": 10,
                "float": 5.150,
                "bignum": 9223372036854775807,
                "string": "simplejson",
                "bool": true
        }
    }`))
    if err != nil {
        panic(err)
        os.Exit(1)
    }
    arr, _ := js.Get("test").Get("array").Array()
    i, _ := js.Get("test").Get("int").Int()
    ms := js.Get("test").Get("string").MustString()
    fmt.Println(arr)
    fmt.Println(i)
    fmt.Println(ms)
}

生成JSON

刚才讲的是解析函数,那么对应的就一定有生成函数,生成函数定义也很简单:

func Marshal(v interface{}) ([]byte, error)
JSON
type Server struct {
    ServerName string
    ServerIP string
}

type Serverslice struct {
    Servers []Server
}

func main() {
    var s Serverslice
    s.Servers = append(s.Servers, Server{"Local_Web", "127.0.0.1"})
    s.Servers = append(s.Servers, Server{"Local_DB", "127.0.0.2"})
    b, err := json.Marshal(s)
    if err != nil {
        fmt.Println("json err: ", err)
    }
    fmt.Println(string(b))
}
structJSONstruct tagXML
type Server struct {
    ServerName string `json:"serverName"`
    ServerIP string `json:"serverIP"`
}

type Serverslice struct {
    Servers []Server `json:"servers"`
}
JSONstruct tag
tag-JSONtagJSONtagomitemptyJSONboolstringintint64tag,stringJSONJSON
Marshal
JSONstringkeymapmap[string]TChannelcomplexfunctionJSONJSONnull