locked
Json C# Consume API RRS feed

  • Question

  • User-1536371215 posted

    I am consuming a JSON feed from a restful API.

    Here is the Jason...SImple :-)

    {CSCLNT:1111,CSPROF:Eric ,CSUACT:A,CCLTNM:A ,CWEBLN:AAA ,CWEBFN:A }

    Code to consume

    var client = new WebClient();
    var JsonResponse = client.DownloadString(url).ToString().Replace("\\", string.Empty);
    dynamic stuff = JsonConvert.DeserializeObject(JsonResponse);
    foreach (var item in stuff)
    {
    Console.WriteLine("{0} {1}", item.CSCLNT, item.CSPROF);
    }
    return "a";
    }

    The Error I get is from the highlighted code 

    Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''char' does not contain a definition for 'CSCLNT''

    This makes no sense to me...any thoughts?

    Friday, October 19, 2018 12:45 PM

All replies

  • User475983607 posted

    I recommend reading the following support doc which explains how is call REST endpoints using C# code and deserialize the response.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

    The main issue with the code show is the "stuff" variable is a string.  Therefore the foreach loop is enumerating over each character in the "stuff" string and placing the character in "item".

    I also recommend learning how to use the Visual Studio Debugger.  Set a breakpoint and single step through the code.  Use the Watch Window to view the variable values.

    https://docs.microsoft.com/en-us/visualstudio/debugger/getting-started-with-the-debugger?view=vs-2017

    Friday, October 19, 2018 1:17 PM
  • User-1536371215 posted

    Thank you.  I will look at the REST doc.  I am grateful for the resource! 

    However, I have breakpoints down pretty well :-)

    Friday, October 19, 2018 1:29 PM
  • User475983607 posted

    However, I have breakpoints down pretty well :-)

    Set a breakpoint in the foreach loop and you should see the "item" var contains a Char() and not a complex type.

    Friday, October 19, 2018 3:15 PM
  • User-474980206 posted
    You json string is not valid json, so it won’t parse correctly.
    Saturday, October 20, 2018 3:57 PM
  • User1724605321 posted

    Hi Smoke.Bear ,

    That method could be used to deserializes the JSON string to a .NET object  , you can refer to below link for checking the Json online:

    https://jsonlint.com/ 

    Best Regards,

    Nan Yu

    Monday, October 22, 2018 5:31 AM
  • User-1536371215 posted

    Thank You!  

    I am getting the JSON back and can see the issue, but I am not sure what to do about it.

    Here is what I am sending from the API side :

    {\"CSCLNT\":\"111\",\"CSPROF\":\"aba \",\"CSUACT\":\"c\",\"CCLTNM\":\" \",\"CWEBLN\":\"ASDAA \",\"CWEBFN\":\"ASASAS \"}

    That works perfectly.  But when I consume on the recieving side  using 

    string JsonResponse = System.Text.UTF8Encoding.UTF8.GetString(client.DownloadData(url));

    It come back with Escaped double quote characters on each end.  

    \"{\"CSCLNT\":\"111\",\"CSPROF\":\"aba \",\"CSUACT\":\"c\",\"CCLTNM\":\" \",\"CWEBLN\":\"ASDAA \",\"CWEBFN\":\"ASASAS \"}\"

    That is what is killing my JSON deserialization.  How can I fix that with doing all sorts of string manipulation?  There has to be a clean way.

    Thank you!

    Monday, October 22, 2018 5:05 PM
  • User475983607 posted

    That works perfectly.  But when I consume on the recieving side  using 

    string JsonResponse = System.Text.UTF8Encoding.UTF8.GetString(client.DownloadData(url));

    That is what is killing my JSON deserialization.  How can I fix that with doing all sorts of string manipulation?  There has to be a clean way.

    Correct, the code shown purposefully converts a JSON stream into a string!  Stop doing that and take the time to read the links in my first thread.  The docs explains, with code examples, how to call a Web API end point and convert the result into an object.

    Here is a basic example based on the linked docs...

    API

            public Product Get(int id)
            {
                return new Product() { Name = "Hello World!" };
            }

    Model

        public class Product
        {
            public string Name { get; set; }
        }

    Client

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ApiConsoleClient
    {
        class Program
        {
            static HttpClient client = new HttpClient();
            static void Main(string[] args)
            {
    
                RunAsync().GetAwaiter().GetResult();
            }
    
    
            static async Task RunAsync()
            {
                string path = "api/values/1";
                Product product = new Product();
    
                product = await GetProductAsync(path);
                ShowProduct(product);
    
            }
    
            static void ShowProduct(Product product)
            {
                Console.WriteLine($"Name: {product.Name}");
            }
    
            static async Task<Product> GetProductAsync(string path)
            {
                Product product = null;
                client.BaseAddress = new Uri("http://localhost:52803");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = await client.GetAsync(path);
                if (response.IsSuccessStatusCode)
                {
                    product = await response.Content.ReadAsAsync<Product>();
                }
                return product;
            }
        }
    
        public class Product
        {
            public string Name { get; set; }
        }
    }
    

    Monday, October 22, 2018 6:16 PM
  • User753101303 posted

    Hi,

    It's common to see a service that returns an explicitely serialiazed object as a string which is then serialized again by ASP.NET (because ASP.NET handles this ouf of the box) which causes the "double serialization" issue.

    So your service should consume and return objects and ASP.NET will handle serializing/deserializing behind the scene.

    Wednesday, November 28, 2018 2:09 PM