Newer
Older
01_hello / struct / json.go
yhornisse on 25 Sep 2021 636 bytes add struct sample
package main

import (
	"fmt"
	"encoding/json"
)

type SampleStruct1 struct {
	Id int64
	Name string
}


type SampleStruct2 struct {
	TestName string `json:"test_name"`
}


func main() {
	v1 := SampleStruct1{1, "taro"}
	if data, err := json.Marshal(v1); err == nil {
		fmt.Printf("%s\n", data) // {"Id":1,"Name":"taro"}

		v2 := SampleStruct1{}
		if err := json.Unmarshal(data, &v2); err == nil {
			fmt.Println(v2) // {1 taro}
		}
	} else {
		fmt.Println(err)
	}

	v3 := SampleStruct2{}
	if err := json.Unmarshal([]byte("{ \"test_name\": \"hoge-\" }"), &v3); err == nil {
		fmt.Println(v3) // {hoge-}
	} else {
		fmt.Println(err)
	}
}