mirror of
https://github.com/golang/go.git
synced 2025-12-08 06:10:04 +00:00
encoding/json: add an example for RawMessage
RawMessage is useful and mildly non-obvious. Given the frequency with which RawMessage questions show up on golang-nuts, and get answered with an example, I suspect adding an example to the docs might help. R=golang-dev, adg CC=golang-dev https://golang.org/cl/14190044
This commit is contained in:
parent
d38ed2a9f2
commit
0857045818
1 changed files with 46 additions and 0 deletions
|
|
@ -81,3 +81,49 @@ func ExampleDecoder() {
|
||||||
// Sam: Go fmt who?
|
// Sam: Go fmt who?
|
||||||
// Ed: Go fmt yourself!
|
// Ed: Go fmt yourself!
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// This example uses RawMessage to delay parsing part of a JSON message.
|
||||||
|
func ExampleRawMessage() {
|
||||||
|
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 interface{}
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
// Output:
|
||||||
|
// YCbCr &{255 0 -10}
|
||||||
|
// RGB &{98 218 255}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue