golang实用技巧之json序列化和反序列化

package main

import (
	"encoding/json"
	"log"
	"reflect"

	"github.com/sanity-io/litter"
)

func main()  {
	type Item struct {
		Id int `json:"id"`
		Num int `json:"num"`
	}
	var itemMap = make(map[int]*Item)
	itemMap[1] = &Item{Id:1, Num:100}
	data, err := json.Marshal(itemMap)
	if err != nil {
		log.Println(err.Error())
		return
	}

	targetItem := make(map[int]*Item)
	// must pass pointer
	// json.Unmarshal(data, targetItem) will no use, just a copy of targetItem..
	json.Unmarshal(data, &targetItem)
	litter.Dump(targetItem)
	litter.Dump(reflect.DeepEqual(targetItem, itemMap))

}
output:
map[int]*main.Item{
  1: &main.Item{
    Id: 1,
    Num: 100,
  },
}
true

  

转载于:https://www.cnblogs.com/LittleLee/p/9387865.html

你可能感兴趣的:(golang实用技巧之json序列化和反序列化)