当JSON字符串中给定了struct类型时,如何将JSON字符串解封为struct。这是我的密码:
package main
import (
"fmt"
"encoding/json"
)
type ServiceResult struct {
Type string `json:"type"`
Content interface{} `json:"content"`
}
type Person struct {
Name string `json:"name"`
}
func main() {
nikola := ServiceResult{}
nikola.Type = "Person"
nikola.Content = Person{"Nikola"}
js, _ := json.Marshal(nikola)
fmt.Println("Marshalled object: " + string(js))
}现在,我想从这个JSON字符串中创建一个新的人,但是必须从JSON字符串中读取该类型。
{"type":"Person","content":{"name":"Nikola"}}发布于 2017-11-01 09:29:06
首先,对于你的类型
type ServiceResult struct {
Type string `json:"type"`
Content interface{} `json:"content"`
}您需要通过定义一个方法来实现“自定义JSON解组器”:
func (sr *ServiceResult) UnmarshalJSON(b []byte) error为了使您的类型满足encoding/json.Unmarshaler接口--这将使JSON解码器在解封送处理到该类型的值时调用该方法。
在该方法中,可以使用助手类型。
type typedObject struct {
Type string `json:"type"`
Content json.RawMessage `json:"content"`
}首先将该b片解编组到其中。
如果解封送处理完成了产生错误的w/o,则typedObject类型的值将使字符串描述其Type字符串中的类型,而包含在其Content字段中的"content“字段中的原始(未解析) JSON字符串。
然后执行switch (或地图查找或其他任何操作)来选择实际的Go类型,将Content字段中的任何数据解封到其中,如下所示:
var value interface{}
switch sr.Type {
case "person":
value = new(Person)
case "car":
value = new(Car)
}
err = json.Unmarshal(sr.Content, value)…如果这些Person和Car是具体的结构类型,可以适当地武装起来供encoding/json使用。
发布于 2017-11-01 09:28:57
当您从ServiceResult创建实例时,您也可以使用person插入内容,然后解压缩它:
service := ServiceResult{Content: Person{}}
json.Unmarshal(data, &service)https://stackoverflow.com/questions/47051538
复制相似问题