动态创建结构

时间:2019-11-25 20:44:59

标签: go

我想使用其API在json中与应用程序通信。

此应用程序具有一个包含以下字段的结构:

CustomFields interface{} `json:"custom_fields,omitempty"`

调用API时,该部分可能类似于:

"custom_fields": {
  "Field1": "Value1",
  "Field2": "Value2"
}

自定义字段的字段名称不固定。可以在应用程序中设置它们。所以我不能只创建一个结构。我需要在代码内部动态构建该结构。有可能吗?

3 个答案:

答案 0 :(得分:0)

构建JSON时,您可以为该interface{}变量使用任何结构:

data.CustomFields=myStructVar

以上,myStructVar是可以编组为JSON的任何结构。

如果您的自定义字段没有结构,则可以使用map[string]interface{}

data.CustomFields=map[string]interface{}{"field1":"value1",
"field2":"value2"}

在解组JSON输入时,如果interface{}自定义字段是JSON对象,则将解封为map[string]interface{},如果是JSON数组,则将解封为[]interface{}。原始值之一(字符串,float64,布尔)。

答案 1 :(得分:0)

使用map[string]interface{}代替自定义字段使用空接口。

type Payload struct {
    Field1 string `json:"field1"`
    Field2 int `json:"field2"`
    CustomFields map[string]interface `json:"customFields,omitempty`
}

Full working example

答案 2 :(得分:0)

我做了这段代码...
似乎无法正常工作,我做错了什么?

tenantCustomFields := d.Get("custom_field").(*schema.Set).List()               

  cf := make(map[string]interface{})                                             
  for _, customFieldRaw := range tenantCustomFields {                            
    customField := customFieldRaw.(map[string]interface{})                         
    customFieldName := customField["name"].(string)                                
    customFieldType := customField["type"].(string)                                
    customFieldValue := customField["value"].(string)                              

    if customFieldType == "string" {                                               
      cf[customFieldName] = customFieldValue                                         
    } else if customFieldType == "integer" {                                       
      cfIntValue, err := strconv.ParseInt(customFieldValue, 10, 64)                  
      if err == nil {                                                                
        return err                                                                     
      }                                                                              
      cf[customFieldName] = cfIntValue                                               
    } else if customFieldType == "boolean" {                                       
      cfBoolValue, err := strconv.ParseBool(customFieldValue)                        
      if err == nil {                                                                
        return err                                                                     
      }                                                                              
      cf[customFieldName] = cfBoolValue                                              
    }                                                                              
  }