英文:
How to unmarshal escaped JSON string with UnmarshalJSON
问题
我正在尝试解析以下JSON字符串:
token = `{
	"id": 1,
	"token": {
		"id": 2248637,
		"metadata": {
			"name": "Name #1",
			"formats": "[{\"mimeType\": \"model/gltf-binary\", \"uri\": \"uri1\"}, {\"mimeType\": \"image/gif\", \"uri\": \"uri2\"}]"
		}
	}
}`
我可以像这样使用两个阶段进行解析。然而,我想使用自定义的unmarshalJSON方法,但是失败了,出现了错误:
我的代码如下:
type FileFormat struct {
   MIMEType string
   URI      string
}
func (format *FileFormat) UnmarshalJSON(data []byte) error {
	var aux []interface{}
	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}
	format.MIMEType = aux[0].(string)
	format.URI = aux[1].(string)
	return nil
}
type TokenMetadata struct {
	Name    string       `json:"name"`
	Formats []FileFormat `json:"formats"`
}
type Token struct {
	ID       TokenID       `json:"tokenId"`
	Metadata TokenMetadata `json:"metadata"`
}
func main() {
	var tokenRes OwnedToken
	if err := json.Unmarshal([]byte(token), &tokenRes); err != nil {
		fmt.Println(err)
	}
}
错误信息为:
json: cannot unmarshal string into Go struct field TokenMetadata.token.metadata.formats of type []main.FileFormat
你如何解决这个问题?非常感谢!
英文:
I'm trying to unmarshal the following JSON string
token = `{
	"id": 1,
	"token": {
		"id": 2248637,
		"metadata": {
			"name": "Name #1",
			"formats": "[{\"mimeType\": \"model/gltf-binary\", \"uri\": \"uri1\", {\"mimeType\": \"image/gif\", \"uri\": \"uri2\"}]"
		}
	}`
I can unmarshal it with 2 phases like this. However, I would like to use custom unmarshalJSON but I fail. I got error
My code as follow:
type FileFormat struct {
   MIMEType string
   URI      string
}
func (format *FileFormat) UnmarshalJSON(data []byte) error {
	var aux []interface{}
	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}
	format.MIMEType = aux[0].(string)
	format.URI = aux[1].(string)
	return nil
}
type TokenMetadata struct {
	Name         string `json:"name"`
	Formats      []FileFormat `json:"formats"`
}
type Token struct {
	ID          TokenID       `json:"tokenId"`
	Metadata    TokenMetadata `json:"metadata"`
}
func main() {
	var tokenRes OwnedToken
	if err := json.Unmarshal([]byte(token), &tokenRes); err != nil {
		fmt.Println(err)
	}
}
And the error is
json: cannot unmarshal string into Go struct field TokenMetadata.token.metadata.formats of type []main.FileFormat
How can I fix this problem? Many thanks!
答案1
得分: 1
以下是翻译好的内容:
文件格式的JSON数组是双重编码的。声明一个与该数组对应的Go类型。在该类型的UnmarshalJSON方法中进行双重解码。
type FileFormats []FileFormat
func (ff *FileFormats) UnmarshalJSON(data []byte) error {
    var s string
    if err := json.Unmarshal(data, &s); err != nil {
        return err
    }
    return json.Unmarshal(
        []byte(s),
        (*[]FileFormat)(ff))
}
type TokenMetadata struct {
    Name    string      `json:"name"`
    Formats FileFormats `json:"formats"`
}
注意:从*FileFormats到*[]FileFormat的转换是为了防止递归。
英文:
The JSON array of file formats is double encoded. Declare a Go type corresponding to the array. Double decode in the UnmarshalJSON method for that type.
type FileFormats []FileFormat
func (ff *FileFormats) UnmarshalJSON(data []byte) error {
	var s string
	if err := json.Unmarshal(data, &s); err != nil {
		return err
	}
	return json.Unmarshal(
		[]byte(s),
		(*[]FileFormat)(ff))
}
type TokenMetadata struct {
	Name    string      `json:"name"`
	Formats FileFormats `json:"formats"`
}
Note: The conversion from from *FileFormats to *[]FileFormat is required to prevent recursion.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论