0

Good Afternoon all,

I am writing a program that calls and API, maps the json response to a corresponding data model. then will ultimately write those maps to disk.

The following code snippet is the main entry point for the program.

  public static async Task Main(string[] args)
    {
        try
        {
            await WriteFile(2010);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"There was an exception: {ex.ToString()}");
        }
    }

    public static async Task WriteFile(int year)
    {

        ApiHelper.InitializeClient();
        var data = await DataLoader.LoadData(year);
        StreamWriter writer = new StreamWriter(@"Data.txt");
        writer.WriteLine(data.Id);
        writer.Close();

    }

The DataLoader is as follows

 public static async Task<BigDataModel> LoadData(int year)
    {

        using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(GetUri(year)))
        {
            if (response.IsSuccessStatusCode)
            {
                DataModel data = await response.Content.ReadAsAsync<DataModel>();            
                return data.Meta;

            }    
            else
            {
                throw new Exception(response.ReasonPhrase); 
            }
        }
    }

Within the if statement the program returns an exception regarding my json format being incorrect and needing to be deserialized. I have tested this system without attempting to map and array and it works correctly.

My Data Models are as followed

 public class DataModel
{          
    public BigDataModel Meta { get; set; }
}

 public class BigDataModel
{
    public int Id { get; set; }
}



expected Json response
{
"projected":"value",
"actual":"value",
"meta":["data":"1","id":"data"]
}

What are the best practices when mapping a json object(array) to an object. Is deserialization a must or can I create a work around to write the data to disk.

  • 2
    your meta property is an object, but is surrounded as an array and as such is invalid json, as it's an array with attributes, is that a copy past error on your part? So, it doesn't have anything to do with `async` but with wrong data, which is exactly what the error message is trying to tell you – Icepickle Sep 26 '19 at 20:07
  • Thank you. I removed the meta from the data model and it executes as expected. I am currently attempting to map the "meta" data to the BigDataModel. – King Solomon Sep 26 '19 at 21:15
  • If you are expecting an array for the Meta Property, define it as Public BigDataModel[] Meta { get; set;} on the DataModel object and you should be right. – Ryan Dobbs Sep 27 '19 at 00:08
  • Your data c# model doesn't match your JSON. To generate a correct model automatically, try using some of the tools from [*How to auto-generate a C# class file from a JSON object string*](https://stackoverflow.com/q/21611674/3744182). – dbc Sep 27 '19 at 19:48

0 Answers0