当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


GO RawMessage用法及代码示例

GO语言"encoding/json"包中"RawMessage"类型的用法及代码示例。

RawMessage 是原始编码的 JSON 值。它实现了 Marshaler 和 Unmarshaler,可用于延迟 JSON 解码或预计算 JSON 编码。

用法:

type RawMessage []byte

示例(元帅):

此示例使用 RawMessage 在编组期间使用预先计算的 JSON。

package main

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

func main() {
    h := json.RawMessage(`{"precomputed": true}`)

    c := struct {
        Header *json.RawMessage `json:"header"`
        Body   string           `json:"body"`
    }{Header: &h, Body: "Hello Gophers!"}

    b, err := json.MarshalIndent(&c, "", "\t")
    if err != nil {
        fmt.Println("error:", err)
    }
    os.Stdout.Write(b)

}

输出:

{
	"header": {
		"precomputed": true
	},
	"body": "Hello Gophers!"
}

示例(解组):

此示例使用 RawMessage 来延迟解析部分 JSON 消息。

package main

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

func main() {
    type Color struct {
        Space string
        Point json.RawMessage // delay parsing until we know the color space
    }
    type RGB struct {
        R uint8
        G uint8
        B uint8
    }
    type YCbCr struct {
        Y  uint8
        Cb int8
        Cr int8
    }

    var j = []byte(`[
    {"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
    {"Space": "RGB",   "Point": {"R": 98, "G": 218, "B": 255}}
]`)
    var colors []Color
    err := json.Unmarshal(j, &colors)
    if err != nil {
        log.Fatalln("error:", err)
    }

    for _, c := range colors {
        var dst any
        switch c.Space {
        case "RGB":
            dst = new(RGB)
        case "YCbCr":
            dst = new(YCbCr)
        }
        err := json.Unmarshal(c.Point, dst)
        if err != nil {
            log.Fatalln("error:", err)
        }
        fmt.Println(c.Space, dst)
    }
}

输出:

YCbCr &{255 0 -10}
RGB &{98 218 255}

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 RawMessage。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。