我正在尝试从json字符串中解析出特定字段,目前我有以下代码段。
package main
import (
"encoding/json"
"fmt"
)
type PlatformID string
type Map map[string]interface{}
func Str2Map(str string) (Map, error) {
var dictionary Map
bytes := []byte(str)
err := json.Unmarshal(bytes, &dictionary)
if err != nil {
fmt.Println(err)
}
return dictionary, err
}
func parsePlatformID(str string) (PlatformID, error) {
fmt.Println(str)
dict, err := Str2Map(str)
fmt.Println(dict)
return dict["platform-id"].(PlatformID), err
}
func main() {
PlatformDictStr := "{\"platform-id\":\"platform_BnjliXLEUV26\",\"platform-labels\":\"test\",\"OptimizeScheme\":\"None\"}"
fmt.Println(PlatformDictStr)
ID, _ := parsePlatformID(PlatformDictStr)
fmt.Println(ID)
}
当我尝试运行它时,它给了我以下错误
{"platform-id":"platform_BnjliXLEUV26","platform-labels":"test","OptimizeScheme":"None"}
{"platform-id":"platform_BnjliXLEUV26","platform-labels":"test","OptimizeScheme":"None"}
map[platform-id:platform_BnjliXLEUV26 platform-labels:test OptimizeScheme:None]
panic: interface conversion: interface is string, not main.PlatformID
goroutine 1 [running]:
panic(0x126aa0, 0x10532300)
/usr/local/go/src/runtime/panic.go:500 +0x720
main.parsePlatformID(0x13e6fe, 0x58, 0x0, 0x0, 0x0, 0x0)
/tmp/sandbox256874711/main.go:26 +0x220
main.main()
/tmp/sandbox256874711/main.go:34 +0x100
这个问题回答了我为什么得到panic: interface conversion: interface is string
如果我尝试将类型断言更改string
为PlatformID的基础类型,则它甚至都不会编译tmp/sandbox325023244/main.go:26: cannot use dict["platform-id"].(string) (type string) as type PlatformID in return argument
那么,如何修改该return
行以便可以检索PlatformID?
在使用了更多语法之后,我想我需要同时进行类型转换和类型断言。
所以下面的代码解决了这个问题
return PlatformID(dict["platform-id"].(string)), err
回想一下,我需要先将接口类型声明为基本类型string
,然后从那里可以将类型转换为PlatformID
PS 1:用例是我在请求正文中获得了原始字符串,REST层将解析出字典中的某些字段,然后将其余未解析的字符串转发到API层以进行进一步处理。字典中的键因工作量而异,因此我无法真正将其解组为定义明确的结构。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句