duan1226 2017-01-11 17:03 采纳率: 100%
浏览 40
已采纳

如何将一个空结构封送为一个空数组

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.

  • 写回答

1条回答 默认 最新

  • doukongyong44772 2017-01-11 17:59
    关注

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

    StatisticKey{
        StatisticIdentifier: "id.string",
        ParameterValueItems: []Parameter{},
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器