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

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

Unmarshal sets inner object value as json string

问题

我正在读取来自Firebase的数据,响应的格式是"map[string]interface{}",例如:

  1. 响应: {
  2. Id: 1,
  3. Name: "Marwan",
  4. Career: {
  5. employeer: "mycompany",
  6. salary: "100",
  7. }
  8. }

我有一个结构体如下:

  1. type Employee struct {
  2. Id int
  3. Name string
  4. Career CareerType
  5. }
  6. type CareerType struct {
  7. Employeer string
  8. Salary string
  9. }

当我执行以下操作时:

  1. marshal, _ := json.Marshal(data)
  2. json.Unmarshal(marshal, Employee{})

结果如下:

  1. 响应: {
  2. Id: 1,
  3. Name: "Marwan",
  4. Career: "{\"employeer\":\"mycompany\", \"salary\":\"100\"}"
  5. }

有人知道为什么内部对象(在这种情况下是Career)没有被解组为一个对象吗?难道解组操作不应该隐式地执行这个操作吗?

英文:

I'm reading data from firebase, and the response is as "map[string]interface{}", for example:

  1. Response: {
  2. Id: 1,
  3. Name: "Marwan",
  4. Career: {
  5. employeer: "mycompany",
  6. salary: "100",
  7. }
  8. }

I have a struct as:

  1. type Employee struct {
  2. Id int
  3. Name string
  4. Career CareerType
  5. }
  6. type CareerType struct {
  7. Employeer string
  8. Salary string
  9. }

when I do the following:

  1. marshal, _ := json.Marshal(data)
  2. json.Unmarshal(marshal, Emplyee{})

The result will be as:

  1. Reposnse: {
  2. Id: 1,
  3. Name: "Marwan",
  4. Career: "{\"employeer\":\"mycompany\", \"salary\":\"100\"}"
  5. }

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

当你编排数据时,只需要传入与你的结构体对应的元素。例如:

  1. bytes, _ := json.Marshal(data["Response"])

然后,解组应该按预期工作:

  1. var employee Employee
  2. json.Unmarshal(bytes, &employee)

employee 现在应该如下所示:

  1. {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:

  1. bytes, _ := json.Marshal(data["Response"])

Afterwards unmarshalling should work as expected:

  1. var employee Employee
  2. json.Unmarshal(bytes, &employee)

employee should now look as follows:

  1. {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:

确定