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 :
Advertisement
Something interesting
Tutorials
+18k Golang : Check if a directory exist or not
+11.2k Google Maps URL parameters configuration
+6.7k Golang : Skip or discard items of non-interest when iterating example
+18.7k Unmarshal/Load CSV record into struct in Go
+15k Golang : package is not in GOROOT during compilation
+6.1k Golang : Create new color from command line parameters
+10.1k Golang : Check a web page existence with HEAD request example
+9.2k Golang : Write multiple lines or divide string into multiple lines
+6k Golang : How to verify input is rune?
+17.5k Golang : Linked list example
+17k Golang : Fix cannot convert buffer (type *bytes.Buffer) to type string error
+6.7k Golang : Humanize and Titleize functions