zoukankan      html  css  js  c++  java
  • go语言中 json转换--nil

    go语言中如果一个变量的值为nil,是否能否为json?

    如果能否转换,转换后的结果是什么?

    下面直接看下例子。

    package main
    
    import (
            "encoding/json"
            "fmt"
    )
    
    func main() {
            marshalTest()
    }
    
    
    func marshalTest() {
        b, err := json.Marshal(nil)
        if err != nil {
            fmt.Println("json.Marshal failed:", err)
            return
        }
    
        fmt.Println("result:", string(b))
    }
    

    output:

    result: null
    

    结果输出为"null"。

    也就是说,凡是值为nil的变量,经过json编码后都是"null"。例如,未赋值的指针变量、切片slice等:

    var ptr *int
    var s []int
    

    反过来,如果一个json字符串是"null",经过解析后,转换后的值是什么样呢?

    例如,转换为结构体,转换后为结构体变量的默认值。

    package main
    
    import (
            "encoding/json"
            "fmt"
    )
    
    func main() {
            unmarshalTest()
    }
    
    type Apple struct {
            Size int
            Addr string
            Num *int
    
    }
    
    func unmarshalTest() {
            value := []byte("null")
            a := Apple{}
    
            if err := json.Unmarshal(value, &a); err != nil {
                    fmt.Println("json.Unmarshal failed:", err)
                    return
            }
    
    
            fmt.Printf("result:%+v
    ", a)
    }
    

    output:

    result:{Size:0 Addr: Num:<nil>}
    

    如果"null"作为json字符串,转换为slice后,值为[]

  • 相关阅读:
    小程序解析html(使用wxParse)
    error: the HTTP rewrite module requires the PCRE library
    CMake Error at cmake/boost.cmake:76 (MESSAGE)
    Centos7安装mysql后无法启动,提示 Unit mysql.service failed to load:No such file or directory
    mysql的三种安装方式
    epel源
    cmake
    yum
    wget
    tar指令
  • 原文地址:https://www.cnblogs.com/lanyangsh/p/12113258.html
Copyright © 2011-2022 走看看