首页 > 解决方案 > 使用 JSON 数组发布请求 - 无法以正确的格式发送

问题描述

我有以下需要发布到 API 的 JSON:

{
  "arch": {
    "id": “TrackingCode”
  },
  "nails": [{
    "name": "John"
  }],

  "token": 'RandomCode'
}

所以我这样定义数据:

public class arch
{
    [JsonProperty("id")]
    public string id { get; set; }
}

public class nails
{
    [JsonProperty("name")]
    public string[] name { get; set; }
}

public class Parameter
{
    [JsonProperty("arch")]
    public arch arch { get; set; }

    [JsonProperty("nails")]
    public nails nails{ get; set; }

    [JsonProperty("token")]
    public string token { get; set; }
}

这就是我在序列化它之前初始化 JSON 的方式:

Parameter json = new Parameter
{
    arch = new arch
    {
        id = TrackingId
    },

    nails = new nails
    {
       name = "John"
    }

   token = "randomstuff"
};

但是有一个涉及“名称”字段的语法/格式错误,不允许编译。显然是那个元素的数组结构。我在做什么错误的语法?

标签: c#json

解决方案


在您的参数对象中更改nails nailsnails[]IEnumerable<nail> nails。您的 json 没有按照您的意愿出现的原因是因为 nails 是一个对象,因此单个实​​体与数组是您想要的多个实体


推荐阅读