go 测试和文件-练习

时间:2024-04-28 19:29:04
package util

import (
	"encoding/json"
	"log"
)

type Monster struct {
	Name  string `json:"name"`
	Age   string `json:"age"`
	Skill string `json:"skill"`
}

func Serialize(monster Monster) string {
	marshal, err := json.Marshal(monster)
	if err != nil {
		log.Fatalf("序列化失败 ", err)
	}

	return string(marshal)

}

func UnSerialize(strMonster string) (monster *interface{}) {
	err := json.Unmarshal([]byte(strMonster), monster)
	if err != nil {
		log.Fatalf("反序列化失败 ", err)
	}
	return monster
}

package test

import (
	"testing"
	"wiaf.org/zhouhongjie/demo1/util"
)

func TestSerialize(t *testing.T) {
	monster := util.Monster{
		Name:  "牛魔王",
		Age:   "13",
		Skill: "牛角功",
	}
	serialize := util.Serialize(monster)
	t.Logf(serialize)
}

func TestUnSerialize(t *testing.T) {
	monster := util.UnSerialize("{\"name\":\"牛魔王\",\"age\":\"13\",\"skill\":\"牛角功\"}")
	u, ok := (*monster).(util.Monster)
	if ok {
		t.Log("转换成功 ", u)
	} else {
		t.Log("转换失败  ", u)

	}

}