英文:
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"}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论