2016-03-02 104 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

謝謝!這個對我有用。 –