golang 两个 struct 之间的值赋值问题

2021-03-02 15:53:52 +08:00
 yellowmarlboro

type Resp struct {
	Code int
	Result map[string]interface{}
}

type Info struct {
	Uid string
	PicInfo []Pic
	Tags Tag
}

type Pic struct {
	PicName string
	PicSize int
}

type Tag struct {
	TagType string
	TagName string
}

用 Resp 把某个接口返回的数据加载 接口返回 json 例:

json
{
    "Code": 1,
    "Result": {
        "Userid": 123,
        "Pics": [
            {
                "PicName": "1.jpg",
                "PicSize": 111
            },
            {
                "PicName": "2.jpg",
                "PicSize": 222
            }
        ],
        "TagType": "TypeA",
        "TagName": "S"
    }
}

另外

1421 次点击
所在节点    Go 编程语言
4 条回复
wingoo
2021-03-02 16:08:41 +08:00
1. 如果要完整的赋值, 应该需要一个新的 struct 来对应到 json 的结构
2. Userid -> Uid 名称不一样的问题 可以 tag 里面写 json 的 tag 即可
3. 如果仅仅是获取 json 中的某些值可以考虑 gjson 直接取不用再解析到 struct, 或者直接 map[string]interface
lbaob
2021-03-02 19:39:48 +08:00

type Info struct {
Uid string
PicInfo []Pic
Tags Tag
}
修改为
type Info struct {
Uid string
PicInfo []Pic
Tag
}

并且使用 json tag 命名 json 字段名
tikazyq
2021-03-02 19:49:30 +08:00
interface{} 一把梭,直接扔进去
yellowmarlboro
2021-03-03 14:10:08 +08:00
@wingoo 谢谢 ~
1. 如果新的 struct 对应 json 的话,如何把这个 新 struct 值赋值给 Info ?只能依靠依次赋值吗?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/757672

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX