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 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试