We help IT Professionals succeed at work.
Get Started

C# - JSON Serialization using model

N M
N M asked
on
109 Views
Last Modified: 2019-11-27
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; }
    }

Open in new window


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

Open in new window


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

        }
    }
}

Open in new window

Comment
Watch Question
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
This problem has been solved!
Unlock 1 Answer and 13 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant

An Experts Exchange subscription includes unlimited access to online courses.

Get Started
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE