网站首页 » Golang » Golang Json 的序列化和反序列化

Golang Json 的序列化和反序列化

June 27, 2020 Golang

Json序列化

/**
@author : Kevink
@time : 2020/6/27 2:56 下午
*/
package main

import (
    "encoding/json"
    "fmt"
)

type Student struct {
    Name string
    Age int
    Sex int

}

func main() {
    s := []string{"123", "456", "789"}

    b, _ := json.Marshal(s)
    fmt.Println(string(b))

    stud := Student{"张三", 10, 1}
    b1, _ := json.Marshal(stud)
    fmt.Println(string(b1))

    //切片,每一项是一个student结构体
    var article []Student
    for i:=1;i<10;i++ {
        var item Student
        item.Name = "张三" + fmt.Sprintf("%d", i)
        item.Age = i + 10
        item.Sex = i
        article = append(article, item)
     }

     fmt.Println(article)
        

        // func Marshal(v interface{}) ([]byte, error){} 返回的articleJson 转成string

     articleJson, _ := json.Marshal(article)
     fmt.Println(string(articleJson))

}

结果:

//切片JSON之后
["123","456","789"]

//结构体JSON之后
{"Name":"张三","Age":10,"Sex":1}

//切片,每一项是结构体
[{张三1 11 1} {张三2 12 2} {张三3 13 3} {张三4 14 4} {张三5 15 5} {张三6 16 6} {张三7 17 7} {张三8 18 8} {张三9 19 9}]

//切片,每一项是结构体 json之后
[{"Name":"张三1","Age":11,"Sex":1},{"Name":"张三2","Age":12,"Sex":2},{"Name":"张三3","Age":13,"Sex":3},{"Name":"张三4","Age":14,"Sex":4},{"Name":"张三5","Age":15,"Sex":5},{"Name":"张三6","Age":16,"Sex":6},{"Name":"张三7","Age":17,"Sex":7},"Age":18,"Sex":8},{"Name":"张三9","Age":19,"Sex":9}]

Json 反序列化

//JSON序列化
     var back []Student
     err := json.Unmarshal([]byte(articleJson), &back)
     if err != nil {
         fmt.Println("JSON反序列化失败,",err)
         return
    }

    fmt.Println(back)
添加新评论