troubleshooting Question

C# - JSON Serialization using model

Avatar of N M
N MFlag for Luxembourg asked on
C#JSON
13 Comments1 Solution119 ViewsLast Modified:
I have a C# small console app that I need to run, it consumes an HTTP restful API. My problem is that using JSON I get a "Cannot implement type blahblah with a collection initializer because it does not implement 'System.Collections.IEnumerable' " and I'm lost. Coud you help me please? Posting the relevant part of the code..

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

namespace TESTMEname
{

    public class headers
    {
        public string Request_ID { get; set; } = "XX123456789";
        public string Correlation_ID { get; set; } = "12345678910";
        public string Token { get; set; } = "abcdefghijklmnopqrstuvwxyzetc";
        public string Content_Type { get; set; } = "application/x-www-form-urlencoded";
    }

    public class access
    {
        public string allPs { get; set; } = "allAccounts";
        public string availableAccounts { get; set; } = "allAccounts";
    }

    public class Body
    {
        public access access { get; set; }
        public bool combinedServiceIndicator { get; set; } = false;
        public int frequencyPerDay { get; set; } = 4;
        public bool recurringIndicator { get; set; } = false;
        public string validUntil { get; set; } = "2020-12-31";
    }

    [System.Serializable]
    public class Consent    //RootObject
    {
        public headers headers { get; set; }
        public Body body { get; set; }
    }

and my class is

class Program
    {
        static HttpClient client = new HttpClient();

        static void ShowConsent(Consent cust_consent)
        {
            Console.WriteLine(cust_consent.ToString());
        }

        static async Task<Uri> CreateConsentAsync(Consent cust_consent)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync("http://myniceurl:8001/some/good/url/", cust_consent);

            ShowConsent(cust_consent);

            response.EnsureSuccessStatusCode();

            // return URI of the created resource.
            return response.Headers.Location;
        }

        static async Task<Consent> GetConsentAsync(string path)
        {
            Consent cust_consent = null;

            HttpResponseMessage response = await client.GetAsync(path);

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

            return cust_consent;
        }

When I try to populate I simple can't

        static void Main()
        {

            RunAsync().GetAwaiter().GetResult();
        }



        static async Task RunAsync()
        {
            // Update port # and url in the following line.
            client.BaseAddress = new Uri("http://myurl:8001/etc..../");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            try
            {
                // Create a new cust_consent  <------- fails!!!!!!!
                Consent cust_consent = new Consent
                {
                    cust_consent.headers.Request_ID  = "something",

                    cust_consent.body.access.allPs = "new_value",
                    cust_consent.body.access.availableAccounts = "new_value",
                    cust_consent.body.combinedServiceIndicator = false,
                    cust_consent.body.frequencyPerDay = 4,
                    cust_consent.body.recurringIndicator = false,
                    cust_consent.body.validUntil = "some_date_YYYYMMDD"
			...etc...
                };

                string json = JsonConvert.SerializeObject(cust_consent);
                Console.WriteLine(json);
                Console.WriteLine("----------------------------------------------------------");
                var url = await CreateConsentAsync(cust_consent);

                Console.WriteLine($"Created at {url}");

                ShowConsent(cust_consent);

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();

        }
    }
}
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 13 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 13 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros