V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
yellowmarlboro

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

  •  
  •   yellowmarlboro · Mar 2, 2021 · 2151 views
    This topic created in 1884 days ago, the information mentioned may be changed or developed.
    
    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"
        }
    }
    
    • 如何把 json 的 Result 内外层的 TagType 的值赋给 Info.Tag.TagType,因为实际的字段太多,层级也不一样,所以不想每个单独赋值,有没有什么解决办法,比如 struct 的 tag ?

    另外

    • Info 会去构造 Xml,所以标签名和结构不能变。
    • 还有比如要把 Userid -> Uid 名称不一样的问题
    4 replies    2021-03-03 14:10:08 +08:00
    wingoo
        1
    wingoo  
       Mar 2, 2021
    1. 如果要完整的赋值, 应该需要一个新的 struct 来对应到 json 的结构
    2. Userid -> Uid 名称不一样的问题 可以 tag 里面写 json 的 tag 即可
    3. 如果仅仅是获取 json 中的某些值可以考虑 gjson 直接取不用再解析到 struct, 或者直接 map[string]interface
    lbaob
        2
    lbaob  
       Mar 2, 2021

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

    并且使用 json tag 命名 json 字段名
    tikazyq
        3
    tikazyq  
       Mar 2, 2021
    interface{} 一把梭,直接扔进去
    yellowmarlboro
        4
    yellowmarlboro  
    OP
       Mar 3, 2021
    @wingoo 谢谢 ~
    1. 如果新的 struct 对应 json 的话,如何把这个 新 struct 值赋值给 Info ?只能依靠依次赋值吗?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5210 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 01:13 · PVG 09:13 · LAX 18:13 · JFK 21:13
    ♥ Do have faith in what you're doing.