0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

json の Marshal と Unmarshal の小さなサンプル

0
Last updated at Posted at 2018-12-18

小さなサンプルです。

Unmarshal

byte から instance を。

Unmarshal(main.go)
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var jsonBlob = []byte(`{"Name":"taro", "Age":42}`)
	type Person struct {
		Name string
		Age int
	}
	var p Person
	json.Unmarshal(jsonBlob, &p)
	fmt.Println(p)
}
run
$ go run main.go
{taro 42}

Marshal

instance から byte を。

Marshal(main.go)
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	type Person struct {
		Name string
		Age int
	}
	p := Person{Name: "maru", Age: 24}
	b, _ := json.Marshal(p)
	fmt.Println(b)
	fmt.Println(string(b))
}
run
$ go run main.go
[123 34 78 97 109 101 34 58 34 109 97 114 117 34 44 34 65 103 101 34 58 50 52 125]
{"Name":"maru","Age":24}

以上となります。

(つづいて、 proto.Marshal/Unmarshal のサンプルをやりたいとおもっています。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?