Unmarshal 将内部对象值设置为 json 字符串
Unmarshal sets inner object value as json string
我正在从 firebase 读取数据,响应为“map[string]interface{}”,例如:
Response: {
Id: 1,
Name: "Marwan",
Career: {
employeer: "mycompany",
salary: "100",
}
}
我有一个结构为:
type Employee struct {
Id int
Name string
Career CareerType
}
type CareerType struct {
Employeer string
Salary string
}
当我执行以下操作时:
marshal, _ := json.Marshal(data)
json.Unmarshal(marshal, Emplyee{})
结果将是:
Reposnse: {
Id: 1,
Name: "Marwan",
Career: "{\"employeer\":\"mycompany\", \"salary\":\"100\"}"
}
有谁知道为什么内部对象(在本例中为 Career)没有被解组为一个对象?解组操作不应该隐含地执行此操作吗?
编组数据时,您只需传入与您的结构相对应的元素。例如:
bytes, _ := json.Marshal(data["Response"])
之后解组应该按预期工作:
var employee Employee
json.Unmarshal(bytes, &employee)
employee
现在应该如下所示:
{Id:1 Name:Marwan Career:{Employer:mycompany Salary:100}}
我正在从 firebase 读取数据,响应为“map[string]interface{}”,例如:
Response: {
Id: 1,
Name: "Marwan",
Career: {
employeer: "mycompany",
salary: "100",
}
}
我有一个结构为:
type Employee struct {
Id int
Name string
Career CareerType
}
type CareerType struct {
Employeer string
Salary string
}
当我执行以下操作时:
marshal, _ := json.Marshal(data)
json.Unmarshal(marshal, Emplyee{})
结果将是:
Reposnse: {
Id: 1,
Name: "Marwan",
Career: "{\"employeer\":\"mycompany\", \"salary\":\"100\"}"
}
有谁知道为什么内部对象(在本例中为 Career)没有被解组为一个对象?解组操作不应该隐含地执行此操作吗?
编组数据时,您只需传入与您的结构相对应的元素。例如:
bytes, _ := json.Marshal(data["Response"])
之后解组应该按预期工作:
var employee Employee
json.Unmarshal(bytes, &employee)
employee
现在应该如下所示:
{Id:1 Name:Marwan Career:{Employer:mycompany Salary:100}}