JSON解组后进行地图结构类型转换

我正在尝试在Go中创建某种工厂模式,但是没有任何运气。我希望能够像其他语言一样使用反射来创建带有对象名称的对象/结构。但是,go似乎并没有以我希望的方式支持它,因此我选择了一种更简单的方法(请参见下文),只需使用映射将结构映射到字符串即可。

The issue I've now run into, is that, it initially seems to work based on my testing, however, once I call json.Unmarshal on it, it goes from the correct struct type, to a map[string]interface{}, as if it's almost reverting to the containing object's type?

st := make(map[string]interface{})
st["StructName1"] = s.StructName1{}
st["StructName2"] = s.StructName2{}
//...

fmt.Printf("1) '%+v' '%+v'\n", reflect.ValueOf(st["StructName1"]), reflect.TypeOf(st["StructName1"]))
fmt.Printf("2) '%+v' '%+v'\n", reflect.ValueOf(s.StructName1{}), reflect.TypeOf(s.StructName1{}))

ff := st["StructName1"]
err := json.Unmarshal([]byte(reqBody), &ff)
fmt.Printf("3) '%+v' '%+v'\n", reflect.ValueOf(ff), reflect.TypeOf(ff))

输出:

1) '{V1: V2:{V2v1: V2v2: V2v3:}}' 'structs.StructName1'
2) '{V1: V2:{V2v1: V2v2: V2v3:}}' 'structs.StructName1'

3) 'map[V2:map[V2v1:value1 V2v2:value2 V2v3:value3] V1:"value4"]' 'map[string]interface {}'

Unmarshaling 'succeeds', in that it has no errors, but the type that is printed in 3) is a map[string]interface{}. Any ideas why this is?

Also, assigning ff the struct directly instead of using a map, i.e.

ff := s.StructName1{}

工作完全正常。

另外,如果您对采用这种方法有更好的建议,我将不胜感激。

提前致谢。

评论