douguanya4248 2016-03-02 03:44
浏览 1052
已采纳

在Golang中执行JSON Unmarshal时如何设置默认值到映射值?

I have a struct like this:

package main

import (
    "encoding/json"
    "fmt"
)

type request struct {
    Version    string               `json:"version"`
    Operations map[string]operation `json:"operations"`
}
type operation struct {
    Type   string `json:"type"`
    Width  int    `json:"width"`
    Height int    `json:"height"`
}

func main() {
    jsonStr := "{\"version\": \"1.0\", \"operations\": {\"0\": {\"type\": \"type1\", \"width\": 100}, \"1\": {\"type\": \"type2\", \"height\": 200}}}"
    req := request{
         Version: "1.0",
    }
    err := json.Unmarshal([]byte(jsonStr), &req)
    if err != nil {
        fmt.Println(err.Error())
    } else {
        fmt.Println(req)
    }
}

I can set Version = "1.0" as its default value, but how can I set default value to Width and Height?

  • 写回答

1条回答 默认 最新

  • douci4026 2016-03-02 04:08
    关注

    Write an unmarshal function to set the default values:

    func (o *operation) UnmarshalJSON(b []byte) error {
        type xoperation operation
        xo := &xoperation{Width: 500, Height: 500}
        if err := json.Unmarshal(b, xo); err != nil {
            return err
        }
        *o = operation(*xo)
        return nil
    }
    

    I created a playground example with modifications to the JSON to make it runnable.

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

    报告相同问题?

    悬赏问题

    • ¥15 最小生成树问题 Prim算法和Kruskal算法
    • ¥25 医院住院病人呼叫器设计
    • ¥15 不想和现在的团队合作了,怎么避免他们对程序动手脚
    • ¥30 c++类和数组实验代码
    • ¥20 C语言字符串不区分大小写字典排序相关问题
    • ¥15 关于#python#的问题:我希望通过逆向技术爬取1688搜索页下滑加载的数据
    • ¥15 关于Linux的终端里,模拟实现一个带口令保护的屏保程序遇到的输入输出的问题!(语言-c语言)
    • ¥30 请问,这个嵌入式Linux系统怎么分析,crc检验区域在哪
    • ¥15 二分类改为多分类问题
    • ¥15 Unity微信小游戏上调用ReadPixels()方法报错