dongmiyu8979 2018-03-15 07:37
浏览 65
已采纳

将JSON数组值映射到结构特定变量

Let's say I have this JSON structure:

{
"name":"repo",
"tags":["1.0","2.0","3.0"]
}

And I would like to map it to this Go struct:

type Repository struct {
    Name string `json:"name"`
    Tags []struct {
        Tag   string `json:"??"`
        Sha256 string
    }
}

How can I link the "tags" array JSON value to a struct field?

EDIT: The idea will be to access the tags array value like this repository.Tags[0].Tag.

  • 写回答

1条回答 默认 最新

  • douzhang2092 2018-03-15 07:48
    关注

    Implement json.Unmarshaler on a Tag type:

    package main
    
    import (
        "encoding/json"
        "log"
    )
    
    type Repository struct {
        Name string
        Tags []Tag
    }
    
    type Tag struct {
        Tag    string
        Sha256 string
    }
    
    func (t *Tag) UnmarshalJSON(b []byte) error {
        var s string
    
        if err := json.Unmarshal(b, &s); err != nil {
                return err
        }
    
        t.Tag = s
        return nil
    }
    
    func main() {
        b := []byte(`{ "name":"repo", "tags":["1.0","2.0","3.0"] }`)
    
        var r Repository
        err := json.Unmarshal(b, &r)
        if err != nil {
                log.Fatal(err)
        }
    
        log.Printf("%+v
    ", r)
    }
    

    Try it on the playground: https://play.golang.org/p/ExwWhis0w0V

    Marshaling back to JSON is left as an exercise for the reader.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测