英文:
Unmarshal sets inner object value as json string
问题
我正在读取来自Firebase的数据,响应的格式是"map[string]interface{}",例如:
响应: {
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, Employee{})
结果如下:
响应: {
Id: 1,
Name: "Marwan",
Career: "{\"employeer\":\"mycompany\", \"salary\":\"100\"}"
}
有人知道为什么内部对象(在这种情况下是Career)没有被解组为一个对象吗?难道解组操作不应该隐式地执行这个操作吗?
英文:
I'm reading data from firebase, and the response is as "map[string]interface{}", for example:
Response: {
Id: 1,
Name: "Marwan",
Career: {
employeer: "mycompany",
salary: "100",
}
}
I have a struct as:
type Employee struct {
Id int
Name string
Career CareerType
}
type CareerType struct {
Employeer string
Salary string
}
when I do the following:
marshal, _ := json.Marshal(data)
json.Unmarshal(marshal, Emplyee{})
The result will be as:
Reposnse: {
Id: 1,
Name: "Marwan",
Career: "{\"employeer\":\"mycompany\", \"salary\":\"100\"}"
}
Does anyone have any idea why the inner object (Career in this case) is not being unmarshalled to an object? shouldn't unmarshal operation do this implicitly?
答案1
得分: 1
当你编排数据时,只需要传入与你的结构体对应的元素。例如:
bytes, _ := json.Marshal(data["Response"])
然后,解组应该按预期工作:
var employee Employee
json.Unmarshal(bytes, &employee)
employee
现在应该如下所示:
{Id:1 Name:Marwan Career:{Employer:mycompany Salary:100}}
英文:
When you marshal the data, you would need to only pass in the element that corresponds to your struct. For example:
bytes, _ := json.Marshal(data["Response"])
Afterwards unmarshalling should work as expected:
var employee Employee
json.Unmarshal(bytes, &employee)
employee
should now look as follows:
{Id:1 Name:Marwan Career:{Employer:mycompany Salary:100}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论