Skip to content

json v2 omit zero behavior #22

@lpic10

Description

@lpic10

Hello,

When using json v2, we need to set OmitZeroStructFields to true during unmarshal.
Another option is to replace omitempty by omitzero in the struct tag. Note that the behavior does not change for strings, slices or maps.

See the example below:

package main

import (
        "encoding/json"
        "fmt"

        jsonv2 "encoding/json/v2"

        "github.com/oapi-codegen/nullable"
)

type InnerStruct struct {
        AnotherValue string
}

type TestStruct struct {
        Name             string                                    `json:"name"`
        ValueInt         nullable.Nullable[int]                    `json:"valueInt,omitempty"`
        ValueString      nullable.Nullable[string]                 `json:"valueString,omitempty"`
        ValueStruct      nullable.Nullable[InnerStruct]            `json:"valueStruct,omitempty"`
        ValueMap         nullable.Nullable[map[string]string]      `json:"valueMap,omitempty"`
        ValueMapStruct   nullable.Nullable[map[string]InnerStruct] `json:"valueMapStruct,omitempty"`
        ValueSliceInt    nullable.Nullable[[]int]                  `json:"valueSliceInt,omitempty"`
        ValueSliceString nullable.Nullable[[]string]               `json:"valueSliceString,omitempty"`
        ValueSliceStruct nullable.Nullable[[]InnerStruct]          `json:"valueSliceStruct,omitempty"`
}

func main() {
        var testStruct TestStruct

        testStruct.Name = "test struct"

        buf, _ := json.Marshal(&testStruct)
        buf2, _ := jsonv2.Marshal(&testStruct)
        buf3, _ := jsonv2.Marshal(&testStruct, jsonv2.OmitZeroStructFields(true))

        fmt.Println(string(buf))
        fmt.Println(string(buf2))
        fmt.Println(string(buf3))
}

Then running (requires go 1.25):

GOEXPERIMENT=jsonv2 go run jsontest.go

{"name":"test struct"}
{"name":"test struct","valueInt":0,"valueStruct":{"AnotherValue":""}}
{"name":"test struct"}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions