登录
首页 >  Golang >  Go问答

利用另一个结构的列表对 Golang 结构进行解组

来源:stackoverflow

时间:2024-02-15 23:24:19 417浏览 收藏

golang学习网今天将给大家带来《利用另一个结构的列表对 Golang 结构进行解组》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我正在使用 go 并尝试将 json 解组为包含另一个结构列表的结构。出了问题,它没有解组它,我不明白为什么。还有什么事情你应该做吗?

package main

import (
    "encoding/json"
    "fmt"
)

type FullMessage struct {
    SubMessages []SubMessage `json:sub_messages`
}

type SubMessage struct {
    Value string `json:value`
}

func main() {
    responseBytes := []byte("{  \"sub_messages\":  [ {\"value\": \"testing\"  } ] }")
    myMessage := FullMessage{}
    unmarshalErr := json.Unmarshal(responseBytes, &myMessage)
    fmt.Println(unmarshalErr)
    fmt.Println(myMessage) // should be populated, but it isn't
    fmt.Println(len(myMessage.SubMessages)) // should be 1, is 0
}

正确答案


您需要在结构标记中添加引号,如下所示:

type FullMessage struct {
    SubMessages []SubMessage `json:"sub_messages"`
}

type SubMessage struct {
    Value string `json:"value"`
}

本篇关于《利用另一个结构的列表对 Golang 结构进行解组》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>