我正在使用 golang 开发一个项目,我需要使用 JSON 响应。问题是来自服务器的 JSON 中的值可以类似于
{person: "john"}
或
{person: {name:"john"}}
所以要创建一个结构来捕获它,我有几个选择:
1) 将 person type 设置为 interface{},但这将在以后使用冗余代码来处理该值
2) 将值存储在新属性中,例如 PersonAsString 和 PersonAsObject,这使得代码更加不可预测,因为它意味着要用作其他开发人员的模块
还有其他优点和缺点吗?还有其他关于如何处理未知类型 JSON 字段的建议吗?
最佳答案
另一种选择是使用自定义 JSON 编码和解码函数定义类型。
type Person string
func (p *Person) UnmarshalJSON(b []byte) error {
if strings.HasPrefix(string(*p),"{"){
value := map[string]string{}
json.Unmarshal(b,&value)
*p = Person(value["name"])
}else{
*p = Person(b)
}
return nil
}
func (p Person) MarshalJSON() ([]byte, error) {
return []byte(p),nil
}
type PersonStruct struct{
Person Person `json:"person"`
}
func main(){
one := `{"person": "john"}`
two := `{"person": {name:"john"}}`
result := PersonStruct{}
json.Unmarshal([]byte(one),&result)
fmt.Println(result)
json.Unmarshal([]byte(two),&result)
fmt.Println(result)
}
关于json - 如何在 golang 或一般类型语言中处理 JSON 响应中的不同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51151729/