Go JSON 转化规则

Go语言内置encoding/json包支持JSON序列化和反序列化,有如下转换规则

  • 基本的数据结构映射关系
bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null
  • 当有指针出现在数据结构中时,会转换成指针所指的值。
  • chanel,complex和函数不能转化为有效的JSON文本
  • JSON序列化时,需要定义一个struct结构,支持json tag来扩展功能, 对于未知的json数据结构,支持interface{}作为接收容器
type Computer struct {
  Brand string
  // -:不要解析这个字段
  Name string `json: "-"`
  // omitempty: 字段为0值时,不要解析
  Price float32 `json: "omitempty"`
  // 可以替换的字段
  IsSupportAntCreditPay bool  `json: "huabei,omitempty"`
  HardwareConfiguration []string 
}
func NewDecoder(r io.Reader) *Decoder
func NewEncoder(w io.Writer) *Encoder

实例

package main

import (
	"fmt"
	"encoding/json"
)

type Computer struct {
  Brand string
  Name string
  Price float64
  // 可以替换的字段
  IsSupportAntCreditPay bool  `json: "huabei`
  HardwareConfiguration []string 
}

func main() {
  hc := []string{"RTX2080Ti", "i9-9900k", "32G", "DDR4 XMP", "512G SSD"}
	alienware := Computer {
    Brand: "Alienware",
    Name: "外星人ALWS-R4968S",
    Price: 0,
    IsSupportAntCreditPay:false,
    HardwareConfiguration: hc}
  if b, err := json.Marshal(alienware); err !=nil {
    return 
  } else {  
    fmt.Println(b)
    fmt.Println()
    var computer Computer
    b := []byte(`{
      "Brand": "Alienware",
      "Name": "外星人ALWS-R4968S",
      "Price": 0.0,
      "huabei": "true",
      "HardwareConfiguration": ["i7-8700K", "GTX 1080Ti"]
    }`)
    if err:= json.Unmarshal(b, &computer); err == nil {
      fmt.Println(computer)
      fmt.Println()
    } else {
      fmt.Println(err)
      fmt.Println()
    }
    var unknowJson interface{}
    if err:= json.Unmarshal(b, &unknowJson); err == nil {
      unknowJson, ok := unknowJson.(map[string]interface{})
      if ok {
        for k, v := range unknowJson {
          switch t := v.(type) {
            case string:
              fmt.Println("string:", k, " ", v)
            case float64:
              fmt.Println("float:", k, " ", v)
            case bool:
              fmt.Println("bool:", k, " ", v)
            case []interface{}:
              fmt.Println(k, "is an array:")
              for i, iv := range t {
                fmt.Println(i, iv)
              }
            default:
              fmt.Println("unknow type:", k)
          }
        }
      }
    }
  }
}
posted @ 2019-03-20 00:50  yihailin  阅读(1026)  评论(0编辑  收藏  举报