从字节数组创建一个结构体。

huangapple go评论91阅读模式
英文:

Create a struct from a byte array

问题

你可以使用json.Unmarshal函数将data转换为Person结构体的变量。以下是示例代码:

var person Person
err := json.Unmarshal(data, &person)
if err != nil {
    log.Fatal(err)
}

// 现在你可以使用person变量,它是一个类型为Person的结构体

请注意,json.Unmarshal函数的第二个参数应该是一个指向Person结构体的指针,以便将解析的数据填充到该结构体中。如果解析过程中出现错误,你可以根据需要进行错误处理。

英文:

I use the json.Marshal interface to accept a map[string]interface{} and convert it to a []byte (is this a byte array?)

data, _ := json.Marshal(value)
log.Printf("%s\n", data)

I get this output

{"email_address":"joe@me.com","street_address":"123 Anywhere Anytown","name":"joe","output":"Hello World","status":1}

The underlying bytes pertain to the struct of the below declaration

type Person struct {
	Name           string  `json:"name"`
	StreetAddress  string  `json:"street_address"`
	Output         string  `json:"output"`
	Status         float64 `json:"status"`
	EmailAddress   string  `json:"email_address",omitempty"`
}

I'd like to take data and generate a variable of type Person struct

How do I do that?

答案1

得分: 3

你使用了json.Unmarshal函数:

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name          string  `json:"name"`
	StreetAddress string  `json:"street_address"`
	Output        string  `json:"output"`
	Status        float64 `json:"status"`
	EmailAddress  string  `json:"email_address,omitempty"`
}

func main() {
	data := []byte(`{"email_address":"joe@me.com","street_address":"123 Anywhere Anytown","name":"joe","output":"Hello World","status":1}`)
	var p Person
	if err := json.Unmarshal(data, &p); err != nil {
		panic(err)
	}
	fmt.Printf("%#v\n", p)
}

输出结果:

main.Person{Name:"joe", StreetAddress:"123 Anywhere Anytown", Output:"Hello World", Status:1, EmailAddress:"joe@me.com"}
英文:

You use json.Unmarshal:

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name          string  `json:"name"`
	StreetAddress string  `json:"street_address"`
	Output        string  `json:"output"`
	Status        float64 `json:"status"`
	EmailAddress  string  `json:"email_address",omitempty"`
}

func main() {
	data := []byte(`{"email_address":"joe@me.com","street_address":"123 Anywhere Anytown","name":"joe","output":"Hello World","status":1}`)
	var p Person
	if err := json.Unmarshal(data, &p); err != nil {
		panic(err)
	}
	fmt.Printf("%#v\n", p)
}

Output:

main.Person{Name:"joe", StreetAddress:"123 Anywhere Anytown", Output:"Hello World", Status:1, EmailAddress:"joe@me.com"}

huangapple
  • 本文由 发表于 2016年3月13日 09:57:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/35965579.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定