Unmarshal将内部对象的值设置为JSON字符串。

huangapple go评论79阅读模式
英文:

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}}

huangapple
  • 本文由 发表于 2021年6月15日 14:52:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/67981355.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定