Search code examples
arraysgostructmarshalling

How to marshal an empty struct as an empty array


I'm not sure if the title accurately explains what I'm looking to do so I'll try to give as many details as I can.

I have a struct with nested structs that I am marshalling and sending out to an API. There are some requests that require my lowest level struct to be empty and I need its parent parameter to equal an empty array instead of null. If I use omitempty on the parameter, it will completely remove it from my request and the request will fail. If I use omitempty on the parameter's parameters, it causes the value to be null and the request will fail.

Here are the structs I am using for the request:

// SubscribeRequest is the top level wrapper for ICWS request bodies
SubscribeRequest struct {
    ClientStateIsFresh bool           `json:"clientStateIsFresh"`
    StatisticKeys      []StatisticKey `json:"statisticKeys"`
}

// StatisticKey is a value we want to pull from ICWS reporting
StatisticKey struct {
    StatisticIdentifier string       `json:"statisticIdentifier"`
    ParameterValueItems []Parameter `json:"parameterValueItems"`
}

// Parameter is a filter applied when pulling statistics
Parameter struct {
    ParameterTypeID string `json:"parameterTypeId"`
    Value           string `json:"value"`
}

And I need the marshalled JSON to look like this:

{
    "clientStateIsFresh":true,
    "statisticKeys":
    [
        {
            "statisticIdentifier":"inin.system.interaction:ActiveCalls",
            "parameterValueItems":
            [

            ]
        }
    ]
}

If I have anything other than this, the request fails. I don't get any errors, but it doesn't return any usable data. Any suggestions on how to accomplish this?

*Note: I did try using []*Parameter instead of []Parameter, but it gave me the same result.


Solution

  • If you want an empty array, you have to provide an empty slice.

    StatisticKey{
        StatisticIdentifier: "id.string",
        ParameterValueItems: []Parameter{},
    }