001-Go JSON处理

  在golang中提供的encoding/json包可以编码JSON以及解码JSON数据。

1、编码JSON

  使用json包中的Marshal函数进行编码,源码如下:

func Marshal(v interface{}) ([]byte, error) {
    e := &encodeState{}
    err := e.marshal(v, encOpts{escapeHTML: true})
    if err != nil {
        return nil, err
    }
    return e.Bytes(), nil
}

  (1)将一个结构体转码JSON

package main

import(
    "encoding/json"
    "fmt"
)

type User struct{
    Name    string     `json:"name"`
    Age        int        `json:"age,omitempty"`
    Address    string    `json:"-"`
}

func main(){
    user := []User{
        User{"张三", 23, "山东青岛"},
        User{"李四", 22, "山东潍坊"},
    }

    if data, err := json.Marshal(user); err == nil{
        fmt.Println(string(data))
    }
}

  输出结果:

[{"name":"张三","age":23},{"name":"李四","age":22}]

  说明:json包在解析结构体时,如果遇到key为json的字段标签,则会按照一定规则解析该标签:第一个出现的是字段在JSON串中使用的名字,之后为其他选项,例如omitempty指定空值字段不出现在JSON中。如果整个value为"-",则不解析该字段。

  (2)将一个map类型转换为JSON字符串

package main

import(
    "encoding/json"
    "fmt"
)

func main(){
    student := make(map[string] interface{})

    student["no"] = "20180101"
    student["name"] = "张三"
    student["course"] = []string{
        "语文","数学","英语",
    }

    if data,err := json.Marshal(student); err == nil{
        fmt.Println(string(data))
    }

}

  输出结果:

{"course":["语文","数学","英语"],"name":"张三","no":"20180101"}

 

2、解码JSON

(1)JSON转换map

package main

import(
    "encoding/json"
    "fmt"
)

func main(){
   
    data := `{"course":["语文","数学","英语"],"name":"张三","no":"20180101"}`

    var student = make(map[string] interface{})

    err := json.Unmarshal([]byte(data), &student)

    if err == nil {
        fmt.Println(student["no"])
        fmt.Println(student["name"])
        fmt.Println(student["course"])
    }
}

  注意此处student["course"],不是切片,也不是数组,如果遍历的话会提示:type interface {} does not support indexing。

(2)JSON转结构体

package main

import(
    "encoding/json"
    "fmt"
)

type Student struct{
    Name    string         `json:"name"`
    No        string      `json:"no"`
    Course  []string     `json:"course"`
}

func main(){
    

    data := `{"course":["语文","数学","英语"],"name":"张三","no":"20180101"}`

    var student Student

    err := json.Unmarshal([]byte(data), &student)

    if err == nil {
        fmt.Println(student.No)
        fmt.Println(student.Name)

        for index,value := range student.Course {
            fmt.Printf("%d-->%s\n", index, value)
        }
    }
}

 

posted @ 2018-03-30 22:21  yshy  阅读(238)  评论(0编辑  收藏  举报