码迷,mamicode.com
首页 > Web开发 > 详细

json

时间:2019-01-30 18:19:11      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:[]   ret   roc   int   images   proc   ofo   image   process   

Json数据协议
技术分享图片
Json数据协议

  1. 导入包:Import “encoding/json”
  2. 序列化: json.Marshal(data interface{})
  3. 反序列化: json.UnMarshal(data []byte, v interface{})
package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    UserName string `json:"user_name"`
    NickName string `json:"nick_name"`
    Age int
    Birthday string
    Sex string
    Email string
    Phone string
}

func testStruct() {
    user1 := User{
        UserName:"user1",
        NickName: "阿三",
        Age: 18,
        Birthday: "1999-9-9",
        Sex: "男",
        Email: "1234567890@qq.com",
        Phone: "666666",
    }
    data, err := json.Marshal(user1)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(data))
}

func testMap() {
    var mp map[string]interface{}
    mp = make(map[string]interface{})
    //因为map的值是空接口,所以值可以是任何类型
    mp["username"] = "user1"
    mp["age"] = 16
    mp["sex"] = "女"
    mp["score"] = 99.5

    data, err := json.Marshal(mp)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(data))
}

func testSlice() {
    var s []map[string]interface{}
    var mp map[string]interface{}
    mp = make(map[string]interface{})
    //因为map的值是空接口,所以值可以是任何类型
    mp["username"] = "user66"
    mp["age"] = 17
    mp["sex"] = "女"
    mp["score"] = 100
    s = append(s, mp)

    //因为map的值是空接口,所以值可以是任何类型
    mp["username"] = "user88"
    mp["age"] = 18
    mp["sex"] = "男"
    mp["score"] = 10
    s = append(s, mp)

    data, err := json.Marshal(s)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(data))
}

func main() {
    testStruct()
    testMap()
    testSlice()
}

输出:br/>{"user_name":"user1","nick_name":"阿三","Age":18,"Birthday":"1999-9-9","Sex":"男","Email":"1234567890@qq.com","Phone":"666666"}
{"age":16,"score":99.5,"sex":"女","username":"user1"}
[{"age":18,"score":10,"sex":"男","username":"user88"},{"age":18,"score":10,"sex":"男","username":"user88"}]

Process finished with exit code 0

json

标签:[]   ret   roc   int   images   proc   ofo   image   process   

原文地址:http://blog.51cto.com/5660061/2347953

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!