如何将utf8字符串转换为

如何将utf8字符串转换为

本文介绍了如何将utf8字符串转换为[] byte?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解组包含JSON的 string ,但是 Unmarshal 函数将 [] byte 作为输入.

I want to unmarshal a string that contains JSON,however the Unmarshal function takes a []byte as input.

如何将我的UTF8 string 转换为 [] byte ?

How can I convert my UTF8 string to []byte?

推荐答案

此问题可能是,但仍会回答,因为有更好的替代解决方案:

This question is a possible duplicate of How to assign string to bytes array, but still answering it as there is a better, alternative solution:

使用简单的转化:

[...]

  1. 将字符串类型的值转换为字节类型的切片会产生一个切片,其连续元素是字符串的字节.

所以您可以简单地做:

s := "some text"
b := []byte(s) // b is of type []byte

但是, string =>[] byte 转换会生成字符串内容的副本(必须复制,因为 string 是不可变的,而 [] byte 值不是不可更改的),并且在 string 较大的情况下,效率不高.相反,您可以使用 io.Reader href ="https://golang.org/pkg/strings/#NewReader" rel ="nofollow noreferrer"> strings.NewReader() 将从传递的中读取字符串而不复制它.并且您可以将此 io.Reader 传递给 json.NewDecoder() 并使用 Decoder进行解组.Decode() 方法:

However, the string => []byte conversion makes a copy of the string content (it has to, as strings are immutable while []byte values are not), and in case of large strings it's not efficient. Instead, you can create an io.Reader using strings.NewReader() which will read from the passed string without making a copy of it. And you can pass this io.Reader to json.NewDecoder() and unmarshal using the Decoder.Decode() method:

s := `{"somekey":"somevalue"}`

var result interface{}
err := json.NewDecoder(strings.NewReader(s)).Decode(&result)
fmt.Println(result, err)

输出(在游乐场上尝试):

map[somekey:somevalue] <nil>

注意:调用 strings.NewReader() json.NewDecoder()确实有一些开销,因此,如果您使用的是小型JSON文本,则可以放心将其转换为 [] byte 并使用 json.Unmarshal() ,它不会变慢:

Note: calling strings.NewReader() and json.NewDecoder() does have some overhead, so if you're working with small JSON texts, you can safely convert it to []byte and use json.Unmarshal(), it won't be slower:

s := `{"somekey":"somevalue"}`

var result interface{}
err := json.Unmarshal([]byte(s), &result)
fmt.Println(result, err)

输出是相同的.在游乐场上尝试.

Output is the same. Try this on the Go Playground.

注意:如果通过读取一些 io.Reader (例如文件或网络连接)来获取JSON输入 string ,则可以直接传递 io.Reader 转换为 json.NewDecoder(),而无需先从中读取内容.

Note: if you're getting your JSON input string by reading some io.Reader (e.g. a file or a network connection), you can directly pass that io.Reader to json.NewDecoder(), without having to read the content from it first.

这篇关于如何将utf8字符串转换为[] byte?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:03