从字节数组创建结构
Create a struct from a byte array
我使用json.Marshal
接口接受一个map[string]interface{}
并将其转换为一个[]byte
(这是一个字节数组吗?)
data, _ := json.Marshal(value)
log.Printf("%s\n", data)
我得到这个输出
{"email_address":"joe@me.com","street_address":"123 Anywhere Anytown","name":"joe","output":"Hello World","status":1}
底层字节属于以下声明的结构
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"`
}
我想使用 data
并生成一个 Person struct
类型的变量
我该怎么做?
您使用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"}
我使用json.Marshal
接口接受一个map[string]interface{}
并将其转换为一个[]byte
(这是一个字节数组吗?)
data, _ := json.Marshal(value)
log.Printf("%s\n", data)
我得到这个输出
{"email_address":"joe@me.com","street_address":"123 Anywhere Anytown","name":"joe","output":"Hello World","status":1}
底层字节属于以下声明的结构
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"`
}
我想使用 data
并生成一个 Person struct
我该怎么做?
您使用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"}