我想解组string
包含JSON的a,但是该Unmarshal
函数将a []byte
作为输入。
如何将UTF8转换string
为[]byte
?
这个问题可能是如何将字符串分配给bytes数组的重复,但仍存在答案,因为有更好的替代解决方案:
从转换string
到[]byte
由该规范允许的,使用一个简单的转换:
字符串类型之间的转换
[...]
- 将字符串类型的值转换为字节类型的切片会产生一个切片,其连续元素是字符串的字节。
因此,您可以简单地执行以下操作:
s := "some text"
b := []byte(s) // b is of type []byte
但是,该string => []byte
转换会复制字符串内容(它必须复制,因为string
s是不可变的,而[]byte
值则不是不变的),如果string
s 大,则转换效率不高。相反,您可以创建一个io.Reader
使用方法strings.NewReader()
,该方法将从传递的内容中读取内容,而string
无需对其进行复制。您可以使用以下方法将其传递io.Reader
给json.NewDecoder()
并解组Decoder.Decode()
:
s := `{"somekey":"somevalue"}`
var result interface{}
err := json.NewDecoder(strings.NewReader(s)).Decode(&result)
fmt.Println(result, err)
输出(在Go Playground上尝试):
map[somekey:somevalue] <nil>
注意:调用strings.NewReader()
和json.NewDecoder()
确实会有一些开销,因此,如果您使用的是小型JSON文本,则可以安全地将其转换为[]byte
和使用json.Unmarshal()
,它不会变慢:
s := `{"somekey":"somevalue"}`
var result interface{}
err := json.Unmarshal([]byte(s), &result)
fmt.Println(result, err)
输出是相同的。在Go Playground上尝试一下。
注意:如果要string
通过读取一些内容io.Reader
(例如文件或网络连接)来获取JSON输入,则可以将其直接传递io.Reader
给json.NewDecoder()
,而不必先从中读取内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句