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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?