You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

252 lines
4.9 KiB

  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package fastjson_test
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "log"
  11. "os"
  12. "strings"
  13. )
  14. func ExampleMarshal() {
  15. type ColorGroup struct {
  16. ID int
  17. Name string
  18. Colors []string
  19. }
  20. group := ColorGroup{
  21. ID: 1,
  22. Name: "Reds",
  23. Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
  24. }
  25. b, err := json.Marshal(group)
  26. if err != nil {
  27. fmt.Println("error:", err)
  28. }
  29. os.Stdout.Write(b)
  30. // Output:
  31. // {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
  32. }
  33. func ExampleUnmarshal() {
  34. var jsonBlob = []byte(`[
  35. {"Name": "Platypus", "Order": "Monotremata"},
  36. {"Name": "Quoll", "Order": "Dasyuromorphia"}
  37. ]`)
  38. type Animal struct {
  39. Name string
  40. Order string
  41. }
  42. var animals []Animal
  43. err := json.Unmarshal(jsonBlob, &animals)
  44. if err != nil {
  45. fmt.Println("error:", err)
  46. }
  47. fmt.Printf("%+v", animals)
  48. // Output:
  49. // [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
  50. }
  51. // This example uses a Decoder to decode a stream of distinct JSON values.
  52. func ExampleDecoder() {
  53. const jsonStream = `
  54. {"Name": "Ed", "Text": "Knock knock."}
  55. {"Name": "Sam", "Text": "Who's there?"}
  56. {"Name": "Ed", "Text": "Go fmt."}
  57. {"Name": "Sam", "Text": "Go fmt who?"}
  58. {"Name": "Ed", "Text": "Go fmt yourself!"}
  59. `
  60. type Message struct {
  61. Name, Text string
  62. }
  63. dec := json.NewDecoder(strings.NewReader(jsonStream))
  64. for {
  65. var m Message
  66. if err := dec.Decode(&m); err == io.EOF {
  67. break
  68. } else if err != nil {
  69. log.Fatal(err)
  70. }
  71. fmt.Printf("%s: %s\n", m.Name, m.Text)
  72. }
  73. // Output:
  74. // Ed: Knock knock.
  75. // Sam: Who's there?
  76. // Ed: Go fmt.
  77. // Sam: Go fmt who?
  78. // Ed: Go fmt yourself!
  79. }
  80. // This example uses a Decoder to decode a stream of distinct JSON values.
  81. func ExampleDecoder_Token() {
  82. const jsonStream = `
  83. {"Message": "Hello", "Array": [1, 2, 3], "Null": null, "Number": 1.234}
  84. `
  85. dec := json.NewDecoder(strings.NewReader(jsonStream))
  86. for {
  87. t, err := dec.Token()
  88. if err == io.EOF {
  89. break
  90. }
  91. if err != nil {
  92. log.Fatal(err)
  93. }
  94. fmt.Printf("%T: %v", t, t)
  95. if dec.More() {
  96. fmt.Printf(" (more)")
  97. }
  98. fmt.Printf("\n")
  99. }
  100. // Output:
  101. // json.Delim: { (more)
  102. // string: Message (more)
  103. // string: Hello (more)
  104. // string: Array (more)
  105. // json.Delim: [ (more)
  106. // float64: 1 (more)
  107. // float64: 2 (more)
  108. // float64: 3
  109. // json.Delim: ] (more)
  110. // string: Null (more)
  111. // <nil>: <nil> (more)
  112. // string: Number (more)
  113. // float64: 1.234
  114. // json.Delim: }
  115. }
  116. // This example uses a Decoder to decode a streaming array of JSON objects.
  117. func ExampleDecoder_Decode_stream() {
  118. const jsonStream = `
  119. [
  120. {"Name": "Ed", "Text": "Knock knock."},
  121. {"Name": "Sam", "Text": "Who's there?"},
  122. {"Name": "Ed", "Text": "Go fmt."},
  123. {"Name": "Sam", "Text": "Go fmt who?"},
  124. {"Name": "Ed", "Text": "Go fmt yourself!"}
  125. ]
  126. `
  127. type Message struct {
  128. Name, Text string
  129. }
  130. dec := json.NewDecoder(strings.NewReader(jsonStream))
  131. // read open bracket
  132. t, err := dec.Token()
  133. if err != nil {
  134. log.Fatal(err)
  135. }
  136. fmt.Printf("%T: %v\n", t, t)
  137. var m Message
  138. // while the array contains values
  139. for dec.More() {
  140. // decode an array value (Message)
  141. err := dec.Decode(&m)
  142. if err != nil {
  143. log.Fatal(err)
  144. }
  145. fmt.Printf("%v: %v\n", m.Name, m.Text)
  146. }
  147. // read closing bracket
  148. t, err = dec.Token()
  149. if err != nil {
  150. log.Fatal(err)
  151. }
  152. fmt.Printf("%T: %v\n", t, t)
  153. // Output:
  154. // json.Delim: [
  155. // Ed: Knock knock.
  156. // Sam: Who's there?
  157. // Ed: Go fmt.
  158. // Sam: Go fmt who?
  159. // Ed: Go fmt yourself!
  160. // json.Delim: ]
  161. }
  162. // This example uses RawMessage to delay parsing part of a JSON message.
  163. func ExampleRawMessage() {
  164. type Color struct {
  165. Space string
  166. Point json.RawMessage // delay parsing until we know the color space
  167. }
  168. type RGB struct {
  169. R uint8
  170. G uint8
  171. B uint8
  172. }
  173. type YCbCr struct {
  174. Y uint8
  175. Cb int8
  176. Cr int8
  177. }
  178. var j = []byte(`[
  179. {"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
  180. {"Space": "RGB", "Point": {"R": 98, "G": 218, "B": 255}}
  181. ]`)
  182. var colors []Color
  183. err := json.Unmarshal(j, &colors)
  184. if err != nil {
  185. log.Fatalln("error:", err)
  186. }
  187. for _, c := range colors {
  188. var dst interface{}
  189. switch c.Space {
  190. case "RGB":
  191. dst = new(RGB)
  192. case "YCbCr":
  193. dst = new(YCbCr)
  194. }
  195. err := json.Unmarshal(c.Point, dst)
  196. if err != nil {
  197. log.Fatalln("error:", err)
  198. }
  199. fmt.Println(c.Space, dst)
  200. }
  201. // Output:
  202. // YCbCr &{255 0 -10}
  203. // RGB &{98 218 255}
  204. }
  205. func ExampleIndent() {
  206. type Road struct {
  207. Name string
  208. Number int
  209. }
  210. roads := []Road{
  211. {"Diamond Fork", 29},
  212. {"Sheep Creek", 51},
  213. }
  214. b, err := json.Marshal(roads)
  215. if err != nil {
  216. log.Fatal(err)
  217. }
  218. var out bytes.Buffer
  219. json.Indent(&out, b, "=", "\t")
  220. out.WriteTo(os.Stdout)
  221. // Output:
  222. // [
  223. // = {
  224. // = "Name": "Diamond Fork",
  225. // = "Number": 29
  226. // = },
  227. // = {
  228. // = "Name": "Sheep Creek",
  229. // = "Number": 51
  230. // = }
  231. // =]
  232. }