Golang encoding/json.RawMessage type example

package encoding/json

RawMessage is a raw encoded JSON object. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.

Golang encoding/json.RawMessage type usage example

 package main

 import (
  "encoding/json"
  "fmt"
 )

 type Employee struct {
  Id int
  Name string
  RawMessage *json.RawMessage
 }
 type Secret struct {
  Message string
 }

 func main() {
  sec := Secret{"I love you!"}

  byte1, err := json.Marshal(sec)

  if err != nil {
 fmt.Println(err)
  }

  raw := json.RawMessage(byte1)
  fmt.Printf("Raw Message : %s\n", raw)

  emp := Employee{0, "Adam", &raw}

  byte2, err := json.Marshal(emp)

  if err != nil {
 fmt.Println(err)
  }

  fmt.Printf("Employee's secret message : %s\n", string(byte2))

  // -----------------------
  // unmarshal json.RawMessage

 fmt.Println("------------------------------------")

  var e Employee
  err = json.Unmarshal(byte2, &e)
  if err != nil {
 fmt.Println(err)
  }
  fmt.Printf("emp.Json : %s \n", string(*emp.RawMessage))

  var sec2 Secret
  err = json.Unmarshal([]byte(*e.RawMessage), &sec2)
  if err != nil {
 fmt.Println(err)
  }
  fmt.Printf("Secret Message : %s \n", sec2)

 }

Play at : http://play.golang.org/p/mzzC44h3Nf

Reference :

http://golang.org/pkg/encoding/json/#RawMessage

Advertisement