golang将结构体转换成json,json转换成结构体

go 专栏收录该内容
12 篇文章 0 订阅
1、将结构体转换成json需要用到marshl函数(或者marshlIndent()函数)。

区别:marshl函数没有将json格式化输出,输出是一个json的字符串。----不利于直接查看json的结构。maeshldent函数

可以将json格式化输出,可阅读性提高了。

2、将json字符串转换成结构体需要用到marshl()函数。

实例如下:


package main


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


type Movie struct {
    Title string
    Year int `json:"released"`
    Color bool `json:"color, omitempty"`
    Actors [] string
}

func main (){
     var movies = []Movie{
        {Title: "Casabanca" , Year: 1942 , Color: false ,
            Actors:[] string { "Humphrey Bogart" , "Ingrid Bergman" }},
        {Title: "Casabanca2" , Year: 1962 , Color: true ,
            Actors:[] string { "Humphrey Paul" }},
    }

     data , err := json. Marshal (movies)
     if err != nil {
        log. Fatalf ( "Json marshaling failed:%s" , err)
    }
    fmt. Printf ( "%s \n " , data)
     var movies2 [] struct {Title string }
     // movies2 := make([]Movie, 10)
     if err3 := json. Unmarshal (data, & movies2); err3 != nil {
        log. Fatalf ( "JSON unmarshling failed: %s" , err)
    }
    fmt. Println ( "*****************" , movies2)
     data2 , err2 := json. MarshalIndent (movies, "" , " " )
     if err2 != nil {
        log. Fatalf ( "Json marshlindent failed:%s" , err)
    }
    fmt. Printf ( "%s \n " , data2)
    
    
}


package main

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


type Movie struct {
    Title string
    Year int `json:"released"`
    Color bool `json:"color, omitempty"`
    Actors [] string
}

func main (){
     var movies = []Movie{
        {Title: "Casabanca" , Year: 1942 , Color: false ,
            Actors:[] string { "Humphrey Bogart" , "Ingrid Bergman" }},
        {Title: "Casabanca2" , Year: 1962 , Color: true ,
            Actors:[] string { "Humphrey Paul" }},
    }

     data , err := json. Marshal (movies)
     if err != nil {
        log. Fatalf ( "Json marshaling failed:%s" , err)
    }
    fmt. Printf ( "%s \n " , data)
     var movies2 [] struct {Title string }
     // movies2 := make([]Movie, 10)
     if err3 := json. Unmarshal (data, & movies2); err3 != nil {
        log. Fatalf ( "JSON unmarshling failed: %s" , err)
    }
    fmt. Println ( "*****************" , movies2)
     data2 , err2 := json. MarshalIndent (movies, "" , " " )
     if err2 != nil {
        log. Fatalf ( "Json marshlindent failed:%s" , err)
    }
    fmt. Printf ( "%s \n " , data2)
    
    
}

  • 1
    点赞
  • 1
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值