2016-03-02 99 views
3

我有这样的结构:如何将默认值设置为映射值时执行json Unmarshal golang?

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) 
    } 
} 

我可以设置版本=“1.0”为默认值,但我怎么能默认值设置为宽度和高度?

+1

你的'json'看起来不是有效的,'Unmarshal'返回一个err,所以在'Unmarshal'前面放一个'err:=',我相信你可以调试它你自己,但现在我不明白你的问题,你正在使用'float'来代替'int32',你的'json'似乎不是有效的。 – Datsik

+0

谢谢。我修改了我的代码,现在可以编译和运行。 –

回答

4

写的解组函数来设置默认值:

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 
} 

我创建了一个playground example经过修改的JSON来使其可以运行。

+0

谢谢!这个对我有用。 –