Matt Rowland Matt Rowland - 5 months ago 11
JSON Question

Deserializing Json in Console App

I am creating a Web API endpoint that will act as a service to retrieve our application configurations, do logging, etc. The problem I am running into is being able to deserialize the Json in the console applications.

Setup

public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}


Web API

[HttpGet]
[Route("Person")]
public IHttpActionResult GetPerson()
{
Person person = new Person
{
FirstName = "Steve",
LastName = "Rogers",
DateOfBirth = new DateTime(1920, 7, 4)
};

return Ok(JsonConvert.SerializeObject(person));
}


Console Application

using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost");

var response = client.GetAsync("api/Person").Result;
var data = response.Content.ReadAsStringAsync().Result;
var person = DeserializeJson<Person>(data);
}

public static T DeserializeJson<T>(string input)
{
var result = JsonConvert.DeserializeObject(input);
var result2 = JsonConvert.DeserializeObject(result.ToString());
return JsonConvert.DeserializeObject<T>(result2.ToString());
}


Values


data = "\"{\\"FirstName\\":\\"Steve\\",\\"LastName\\":\\"Rogers\\",\\"DateOfBirth\\":\\"1920-07-04T00:00:00\\"}\""

result = "{\"FirstName\":\"Steve\",\"LastName\":\"Rogers\",\"DateOfBirth\":\"1920-07-04T00:00:00\"}"

result2 = {{
"FirstName": "Steve",
"LastName": "Rogers",
"DateOfBirth": "1920-07-04T00:00:00"
}}


The issue that I am having is that I cannot deserialize into the
Person
object until I have deserialized for the 3rd time. The value in
result2
is the only one I have been able to successfully deserialize into
Person
. Is there a more efficient way to accomplish this deserialization? Preferably without having 3 iterations.

Answer

I was able to get the following to run successfully (based on this Microsoft article):

Console App:

    static void Main(string[] args)
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:3963/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("api/Person");
            Person product = await response.Content.ReadAsAsync<Person>();
        }
    }

Controller:

public class PersonController : ApiController
{
    public Person GetPerson()
    {
        Person person = new Person
        {
            FirstName = "Steve",
            LastName = "Rogers",
            DateOfBirth = new DateTime(1920, 7, 4)
        };
        return person;
    }
}