dongwu4834 2014-12-15 20:49
浏览 188

如何将具有动态字段的JSON对象映射到Go结构

I am developing a website using Go and connecting it to Elastic Search. In Elastic Search I can have dynamic fields for index types. When I read a document from Elastic Search it will return a JSON object as the result, which can include fields with dynamic names (or user defined fields).

I can get the JSON result and unmarshal it into a Go struct, but I do not know what is the best way to keep those dynamic fields as part of the Go struct.

This is what I am doing. For example, if I get a document for a Contact from Elastic Search it may look something like this:

{  
   "EmailAddress": "test@test.com",
   "Name": "Test Contact",
   "Phone": "17894785236",
   "City": "San Francisco",
   "State": "California"
}

And the Go struct for Contact is:

type Contact struct {
    EmailAddress            string
    Name                    string
    Phone                   string
    CustomFields            map[string]interface{}
}

And I implement Marshaler and Unmarshaler to override how the object is Marshaled and Unmarshalled.

func (c *Contact) MarshalJSON() ([]byte, error) {
    contactMap := make(map[string]interface{})
    contactMap["EmailAddress"] = c.EmailAddress
    contactMap["Name"] = c.Name
    contactMap["Phone"] = c.Phone

    for k, v := range c.CustomFields {
        contactMap[k] = v
    }

    return json.Marshal(contactMap)
}

func (c *Contact) UnmarshalJSON(data []byte) error {
    var contactMap map[string]interface{}

    if c == nil {
        return errors.New("RawString: UnmarshalJSON on nil pointer")
    }

    if err := json.Unmarshal(data, &contactMap); err != nil {
        return err
    }

    c.EmailAddress = contactMap["EmailAddress"].(string)
    c.Name = contactMap["Name"].(string)
    c.Phone = contactMap["Phone"].(string)

    for key, val := range contactMap {
        if key != "EmailAddress" && key != "Name" && Key != "Phone" {
            c.CustomFields[key] = value
        }
    }

    return nil
}

Is this the best way to do this? What would you recommend?

  • 写回答

2条回答 默认 最新

  • doubian19900911 2014-12-15 22:08
    关注

    Just add little cleanup

    var contactMap map[string]interface{}
    
    if c == nil {
        return errors.New("RawString: UnmarshalJSON on nil pointer")
    }
    
    if err := json.Unmarshal(data, &contactMap); err != nil {
        return err
    }
    
    for key, val := range contactMap {
        switch key {
            case "EmailAddress":
                c.EmailAddress = val.(string)
            case "Name":
                c.Name = val.(string)
            case "Phone":
                c.Phone = val.(string)
            default:
                c.CustomFields[key] = val
            }
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置