Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Created July 29, 2015 17:15
Show Gist options
  • Save mdwhatcott/8dd2eef0042f7f1c0cd8 to your computer and use it in GitHub Desktop.
Save mdwhatcott/8dd2eef0042f7f1c0cd8 to your computer and use it in GitHub Desktop.
Example of implementing MarshalJSON and UnmarshalJSON to serialize and deserialize custom types to JSON in Go. Playground: http://play.golang.org/p/7nk5ZEbVLw
package main
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
)
func main() {
a := make(Stuff)
a[1] = "asdf"
a[-1] = "qwer"
fmt.Println("Initial: ",a)
stuff, err := json.Marshal(a)
fmt.Println("Serialized: ", string(stuff), err)
b := make(Stuff)
err = json.Unmarshal(stuff, &b)
fmt.Println("Deserialized:", b, err)
}
type Stuff map[int]string
func (this Stuff) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString("{")
length := len(this)
count := 0
for key, value := range this {
jsonValue, err := json.Marshal(value)
if err != nil {
return nil, err
}
buffer.WriteString(fmt.Sprintf("\"%d\":%s", key, string(jsonValue)))
count++
if count < length {
buffer.WriteString(",")
}
}
buffer.WriteString("}")
return buffer.Bytes(), nil
}
func (this Stuff) UnmarshalJSON(b []byte) error {
var stuff map[string]string
err := json.Unmarshal(b, &stuff)
if err != nil {
return err
}
for key, value := range stuff {
numericKey, err := strconv.Atoi(key)
if err != nil {
return err
}
this[numericKey] = value
}
return nil
}
@karl-gustav
Copy link

@UBarney
Copy link

UBarney commented Dec 29, 2020

got panic when run this

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"strconv"
)

func main() {
	withStuff:=new(struct{
		Stuff Stuff `json:"stuff"`
	})

	if err := json.Unmarshal([]byte(`{"stuff":{"1":"a"}}`), withStuff); err != nil {
		fmt.Println("got err",err.Error())
	}
}

type Stuff map[int]string

func (this Stuff) MarshalJSON() ([]byte, error) {
	buffer := bytes.NewBufferString("{")
	length := len(this)
	count := 0
	for key, value := range this {
		jsonValue, err := json.Marshal(value)
		if err != nil {
			return nil, err
		}
		buffer.WriteString(fmt.Sprintf("\"%d\":%s", key, string(jsonValue)))
		count++
		if count < length {
			buffer.WriteString(",")
		}
	}
	buffer.WriteString("}")
	return buffer.Bytes(), nil
}

func (this Stuff) UnmarshalJSON(b []byte) error {
	var stuff map[string]string
	err := json.Unmarshal(b, &stuff)
	if err != nil {
		return err
	}
	for key, value := range stuff {
		numericKey, err := strconv.Atoi(key)
		if err != nil {
			return err
		}
		this[numericKey] = value
	}
	return nil
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment