Skip to content

Instantly share code, notes, and snippets.

@JiaxiangZheng
Created February 24, 2014 08:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JiaxiangZheng/9184001 to your computer and use it in GitHub Desktop.
Save JiaxiangZheng/9184001 to your computer and use it in GitHub Desktop.
This file demonstrates golang's json library to encode&decode, marshal&unmarshal json data.
package main
import (
"encoding/json"
"fmt"
"os"
"log"
)
// 主要是靠Marshal和Unmarshal函数进行解析与读取
// func Marshal(v interface{}) ([]byte, error)
// func Unmarshal(data []byte, v interface{}) error
func MarshalUnmarshal() {
type Message struct {
Name string
Body string
Time int64
}
buf := []byte(`{"Name":"JSON", "Body":"JSON and Golang", "Time":201402041556}`)
var unknown interface{}
err := json.Unmarshal(buf, &unknown)
if err != nil {
fmt.Println("error unmarshal buf")
return
}
fmt.Println(unknown, "\n") // map[Time:2.01402041556e+11 Body:JSON and Golang Name:JSON]
mres := unknown.(map[string]interface{})
for k, v := range mres {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string : ", vv)
case int:
fmt.Println(k, "is int : ", vv)
case []interface{}:
fmt.Println(k, "is an array : ")
for i, u := range vv {
fmt.Println(i, u)
}
case float64:
fmt.Println(k, "is float64 : ", vv)
default:
fmt.Println(k, "is of a type I don't know how to handle")
}
}
fmt.Println()
// if the content of buf contains blank symbol between each field, it's
// unable to unmarshal the correct answer.
var msg Message
err = json.Unmarshal(buf, &msg)
if err != nil {
fmt.Println("error unmarshal msg")
return
}
fmt.Println(msg, "\n") // {JSON JSON and Golang 201402041556}
buf, err = json.Marshal(msg)
fmt.Println(string(buf))
}
func SliceMarshalUnmarshal() {
type Family struct {
Name string
Age int
Parents []string
}
family := Family{"Jiaxiang Zheng", 24, []string{"Zheng", "Chen"}}
buf, err := json.Marshal(family)
if err != nil {
fmt.Println("error marshal family")
return
}
fmt.Println(string(buf))
buf = []byte(`{"Name":"Jiaxiang","Age":24,"Parents":["Huashan","Qirong"]}`)
err = json.Unmarshal(buf, &family)
if err != nil {
fmt.Println("error unmarshal buf")
return
}
fmt.Println(family)
}
type ColorGroup struct {
ID int
Name string
Colors []string
Group *ColorGroup
}
func PointerMarshalUnmarshal() {
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"White", "Red", "Green", "Black"},
Group: &ColorGroup{2, "Tome", []string{"a", "b"}, nil},
}
b, err := json.Marshal(group)
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(string(b))
json.Unmarshal(b, &group)
fmt.Println(group)
buf := []byte(`{"ID":12,"Name":"Jiaxiang Zheng","Colors":["Brown","Red","White"],"Group":{"ID":2,"Name":"Tome","Colors":["Green","Red","Yellow"],"Group":null}}`)
var val ColorGroup
json.Unmarshal(buf, &val)
fmt.Println(val)
fmt.Println(*val.Group)
}
func EncoderDemo() {
fp, err := os.Create("output.json")
if err != nil {
log.Fatalln("error create json file")
return
}
defer fp.Close()
enc := json.NewEncoder(fp)
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"White", "Red", "Green", "Black"},
Group: &ColorGroup{2, "Tome", []string{"a", "b"}, nil},
}
err = enc.Encode(&group)
if err != nil {
log.Fatalln("error encoding json")
return
}
group.ID = 100
group.Name = "Jiaxiang Zheng"
group.Group = nil
err = enc.Encode(&group)
if err != nil {
log.Fatalln("error encoding json")
return
}
}
func DecodeDemo() {
fp, err := os.Open("output.json")
if err != nil {
log.Fatalln("run DecodeDemo first")
return
}
dec := json.NewDecoder(fp)
for {
var group ColorGroup
if err := dec.Decode(&group); err != nil {
break
}
fmt.Println(group)
}
}
func main() {
fmt.Println("**********encoder demo*******************")
EncoderDemo()
fmt.Println("***********decoder demo*****************")
DecodeDemo()
fmt.Println("*************marshal and unmarshal******")
MarshalUnmarshal()
fmt.Println("******slice marshal & unmarshal**********")
SliceMarshalUnmarshal()
fmt.Println("*****pointer marshal & unmarshal********")
PointerMarshalUnmarshal()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment