如何在C#,RestServices中的方括号中构建有效载荷(POST方法)

时间:2019-03-21 21:50:03

标签: c# restsharp xunit

预期的请求:

[
    {
        "ID": 159, //int
        "Name": "Sam", // String
        "Amount": 1    // int
    },
    {
        "ID": 160, //int
        "Name": "SamP", // String
        "Amount": 1    // int
    }
   ]

我必须以这种格式构建请求,但是,在有效载荷的开头和结尾处使用方括号[]遇到了一些麻烦

我对C#,RestServices和Xunit的处理方式如下:

RestServices

public IRestResponse PostIssue(IssueRequest IssueRequest, string Id)
    {
        var baseurl = _endpoint.EndpointURL;
        var resource = _refund.Issue;

        var restClient = new RestClient(baseurl);
        var request = new RestRequest(resource, Method.POST);

        request.RequestFormat = DataFormat.Json;
        request.AddQueryParameter("Id", Id);
        request.AddJsonBody(IssueRequest);

        // EXECUTE REQUEST
        var response = restClient.Execute(request);
        return response;
    }

RequestModel:

 public class IssueRequest
    {
        public Item[] IssueItem { get; set; }
    }
    public class Item
    {
        public int Id { get; set; }
        public int Amount { get; set; }
        public string UserName { get; set; }
    }

XUnit代码:

[Fact]
        public void IssueScenarios()
        {
            //Request Boody
            IssueRequest issueRequest = new IssueRequest
            {
                IssueItem = new Item[]
                {
                    new Item {Id = 159, Amount = 1, Name = "Sam"}
                    new Item {Id = 160, Amount = 1, Name = "Samp"}
                }
            };

            var response = _restServices.PostIssue(issueRequest, ItemID);
            IssueResponse parsedResponse = JsonConvert.DeserializeObject<issueResponse>(response.Content);
}

实际上,我能够构建这样的有效负载:

{"Property1":[{"Id":159,"Amount":1,"Name":"Sam"},{"Id":160,"Amount":1,"Name":"SamP"}]}

但是我需要像

[{"Id":159,"Amount":1,"Name":"Sam"},{"Id":160,"Amount":1,"Name":"SamP"}]

没有任何“ Property1”名称

感谢您的帮助,谢谢

1 个答案:

答案 0 :(得分:1)

序列化基础项目数组

request.AddJsonBody(IssueRequest.IssueItem);