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

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

Create a struct from a byte array

问题

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

  1. var person Person
  2. err := json.Unmarshal(data, &person)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. // 现在你可以使用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?)

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

I get this output

  1. {"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

  1. type Person struct {
  2. Name string `json:"name"`
  3. StreetAddress string `json:"street_address"`
  4. Output string `json:"output"`
  5. Status float64 `json:"status"`
  6. EmailAddress string `json:"email_address",omitempty"`
  7. }

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

How do I do that?

答案1

得分: 3

你使用了json.Unmarshal函数:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type Person struct {
  7. Name string `json:"name"`
  8. StreetAddress string `json:"street_address"`
  9. Output string `json:"output"`
  10. Status float64 `json:"status"`
  11. EmailAddress string `json:"email_address,omitempty"`
  12. }
  13. func main() {
  14. data := []byte(`{"email_address":"joe@me.com","street_address":"123 Anywhere Anytown","name":"joe","output":"Hello World","status":1}`)
  15. var p Person
  16. if err := json.Unmarshal(data, &p); err != nil {
  17. panic(err)
  18. }
  19. fmt.Printf("%#v\n", p)
  20. }

输出结果:

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

You use json.Unmarshal:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type Person struct {
  7. Name string `json:"name"`
  8. StreetAddress string `json:"street_address"`
  9. Output string `json:"output"`
  10. Status float64 `json:"status"`
  11. EmailAddress string `json:"email_address",omitempty"`
  12. }
  13. func main() {
  14. data := []byte(`{"email_address":"joe@me.com","street_address":"123 Anywhere Anytown","name":"joe","output":"Hello World","status":1}`)
  15. var p Person
  16. if err := json.Unmarshal(data, &p); err != nil {
  17. panic(err)
  18. }
  19. fmt.Printf("%#v\n", p)
  20. }

Output:

  1. 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:

确定