简体   繁体   中英

C# JSON - Error: Cannot initialize type with collection initializer (does not implement 'System.Collection.IEnumerable')

I have problem debug the below (in the simplest way possible...). I have a set of properties for a JSON, everything works up to the point that I try to serialize. I would appreciate the simplest way possible to correct, I have to use Newtonsoft. Below the full C# code. The error area is being marked in comments.

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();

        }
    }
}

Your'e using the identifier names inside their own initializer. For example, your'e using cust_some inside Consent initializer. You need to remove them, like so:

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"      
    };
}

Also, please note that per Microsoft naming conventions, all identifiers except parameter names should be capitalized, so eg headers , body , access and so on, both class and property names, should become Headers , Body , Access . You can read about it here .

In partial class body, add first before all the properties that are needed, the below:

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

Now, [ kudos to user ***HeyJude**** - thank you! ] create

            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,
                    frequencyPerDay = 4,
                    recurringIndicator = false,
                    validUntil = "2020-12-31"
                }
            };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM