C#JSON-错误:无法使用集合初始化程序初始化类型(不实现'System.Collection.IEnumerable')

我在调试以下内容时遇到问题(以最简单的方式...)。我有一套JSON属性,一切正常,直到尝试序列化为止。我将不胜感激,因为我不得不使用Newtonsoft。 在完整的C#代码下方。错误区域已在注释中标记。

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace MY_TEST
{
    public partial class headers
    {
        [JsonProperty("RequestID")]
        public string myRequest { get; set; } = "someIDhere";

        [JsonProperty("CorrelationID")]
        public string CorrelationID { get; set; } = "1234567890";

        [JsonProperty("Token")]
        public string Token { get; set; } = "areallylongstringgoeshereastoken";

        [JsonProperty("ContentType")]
        public string Content_Type { get; set; } = "application/x-www-form-urlencoded";
    }

    public partial class access
    {
        [JsonProperty("allPs")]
        public string allPs { get; set; } = "all";

        [JsonProperty("availableaccounts")]
        public string availableaccounts { get; set; } = "all";
    }

    public partial class body
    {
        [JsonProperty("combinedServiceIndicator")]
        public bool combinedServiceIndicator { get; set; } = false;

        [JsonProperty("frequencyPerDay")]
        public int frequencyPerDay { get; set; } = 4;

        [JsonProperty("recurringIndicator")]
        public bool recurringIndicator { get; set; } = false;

        [JsonProperty("validUntil")]
        public string validUntil { get; set; } = "2020-12-31";
    }

    public class Consent    //RootObject
    {
        [JsonProperty("headers")]
        public headers headers { get; set; } 

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

    class Program
    {
        static HttpClient client = new HttpClient();
        static void ShowConsent(Consent cust_some)
        {
            Console.WriteLine(cust_some.ToString());
        }

        static async Task<Uri> CreateConsentAsync(Consent cust_some)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync("http://myurladdr:8001/me/and/you/api/",cust_some);
            ShowConsent(cust_some);
            response.EnsureSuccessStatusCode();
            return response.Headers.Location;
        }

        static async Task<Consent> getconsentAsync(string path)
        {
            Consent cust_some = null;
            HttpResponseMessage response = await client.Getasync(path);

            if (response.IsSuccessStatusCode)
            {
                cust_some = await response.Content.ReadAsAsync<Consent>();
            }

            return cust_some;
        }

        static void Main()
        {

            RunAsync().Getawaiter().GetResult();
        }

        static async Task RunAsync()
        {
            client.BaseAddress = new Uri("http://myurladdr:8001/me/and/you/api/");
            client.DefaultRequestHeaders.accept.Clear();
            client.DefaultRequestHeaders.accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            try
            {
                // >---------- ERROR: Cannot initialize type 'Consent' with a collection initializer because it does not implement 'System.Collection.IEnumerable' ----------<
                Consent cust_some = new Consent
                {
                // Headers
                cust_some.headers.myRequest = "someIDhere",cust_some.headers.CorrelationID = "1234567890",cust_some.headers.Token = "areallylongstringgoeshereastoken"
                cust_some.headers.Content_Type = "application/x-www-form-urlencoded",// Body
                cust_some.body.access.allPs = "all",cust_some.body.access.availableaccounts = "all",cust_some.body.combinedServiceIndicator = false,cust_some.body.frequencyPerDay = 4,cust_some.body.recurringIndicator = false,cust_some.body.validUntil = "2020-12-31"
                };
                // >---------- ERROR ----------<

                string json = JsonConvert.SerializeObject(cust_some,Formatting.Indented);

                Console.WriteLine(json.ToString());
                Console.WriteLine("----------------------------------------------------------");

                Console.WriteLine(json);

                var url = await CreateConsentAsync(cust_some);

                Console.WriteLine($"Created at {url}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();

        }
    }
}
holly00 回答:C#JSON-错误:无法使用集合初始化程序初始化类型(不实现'System.Collection.IEnumerable')

您在自己的初始化程序中使用标识符名称。例如,您在cust_some初始化程序中使用Consent。您需要删除它们,就像这样:

Consent cust_some = new Consent
{
    // Headers
    headers = new headers 
    {
       myRequest = "someIDhere",CorrelationID = "1234567890",Token = "areallylongstringgoeshereastoken"
       Content_Type = "application/x-www-form-urlencoded"
    }
    // Body
    body = new body
    {
        access = new access
        {
            allPs = "all",availableAccounts = "all"
        }
        combinedServiceIndicator = false,frequencyPerDay = 4,recurringIndicator = false,validUntil = "2020-12-31"      
    };
}

此外,请注意,根据Microsoft的命名约定,除参数名称外的所有标识符均应大写,例如类名和属性名的headersbodyaccess等,都应变为HeadersBodyAccess。您可以here来了解它。

,

在部分类主体中,首先在所需的所有属性之前添加以下内容:

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

现在,[感谢用户*** HeyJude ****-谢谢!]创建

            Consent cust_some = new Consent
            {
                headers = new headers
                {
                    myRequest = "someIDhere",Correlation_ID = "1234567890",Token = "areallylongstringgoeshereastoken",Content_Type = "application/json"    //"application/json; charset=utf-8"
                },body = new body
                {
                    access = new access  //this is how to include access in body
                    {
                        allPs = "allAccounts",availableAccounts = "allAccounts"
                    },combinedServiceIndicator = false,validUntil = "2020-12-31"
                }
            };
本文链接:https://www.f2er.com/3029990.html

大家都在问