将interface{}转换为Golang中的结构体

9

我很新于Go语言,正在努力理解所有不同类型及其使用方法。我有一个接口,其中包含以下内容(最初来自json文件):

[map[item:electricity transform:{fuelType}] map[transform:{fuelType} item:gas]]

我有以下结构体:

type urlTransform struct {
        item string
        transform string
}

我不知道如何将接口数据传输到结构体中;我确定这很愚蠢,但我已经尝试了一整天。任何帮助都将不胜感激。

2个回答

7

将JSON直接解码为所需类型,而不是解码为interface{}

声明与JSON数据结构相匹配的类型。使用结构体表示JSON对象,使用切片表示JSON数组:

type transform struct {
    // not enough information in question to fill this in.
}

type urlTransform struct {
    Item string
    Transform transform
}

var transforms []urlTransform

字段名称必须是导出的(以大写字母开头)。

将JSON反序列化为声明的值:

err := json.Unmarshal(data, &transforms)

或者

err := json.NewDecoder(reader).Decode(&transforms)

1
我遇到了错误 cannot use value (type interface {}) as type []byte in argument to json.Unmarshal: need type assertion。我尝试了 err := json.Unmarshal(data.([]byte), &transforms) 但是现在我得到了 panic: interface conversion: interface {} is []interface {}, not []uint8 :( - Katie

3

根据您的回应: [map[item:electricity transform:{fuelType}] map[transform:{fuelType} item:gas]]。如您所见,这是一个包含maparray

从中获取值的一种方法是:

values := yourResponse[0].(map[string]interface{}). // convert first index to map that has interface value.
transform := urlTransform{}
transform.Item = values["item"].(string) // convert the item value to string
transform.Transform = values["transform"].(string)
//and so on...

从上面的代码中可以看出,我正在使用map获取值。并将该值转换为适当的类型,在这种情况下是string

您可以将其转换为适当的类型,如intbool或其他类型。但是这种方法很痛苦,因为您需要逐个获取值并将其分配给您的字段结构。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接