How to set default value to map value when doing json Unmarshal in golang?

huangapple go评论89阅读模式
英文:

How to set default value to map value when doing json Unmarshal in 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,omitempty"`
	Height int    `json:"height,omitempty"`
}

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

我可以将Version设置为"1.0"作为其默认值,但是如何将WidthHeight设置为默认值呢?在结构体中,你可以使用omitempty标签来指定字段的默认值。当字段的值为零值时,将不会在JSON序列化中包含该字段。在operation结构体中,你可以将WidthHeight的标签改为json:"width,omitempty"json:"height,omitempty",这样它们的默认值将会被忽略。

英文:

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

得分: 5

编写一个解析函数来设置默认值:

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示例,对JSON进行了修改以使其可运行。

英文:

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.

huangapple
  • 本文由 发表于 2016年3月2日 11:44:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/35738111.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定