Deserializing Json in a console application

I am creating a web API endpoint that will act as a service to get our application configurations, logging, etc. The problem I am facing is the deserialization of Json in console applications.

Customization

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

Web interface

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

Value

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" 00}}}

The problem I am facing is that I cannot deserialize into a Person object until I deserialize the third time. The value in result2 is the only one that I was able to successfully deserialize in Person . Is there a more efficient way to do this deserialization? Preferably without 3 iterations.

+7
json c # serialization asp.net-web-api deserialization
source share
2 answers

I managed to run the following (based on this Microsoft article ):

Console Application:

  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; } } 
+4
source share

Another solution:

  • Add Newtonsoft.Json to the project.

enter image description here

  1. Add usage to your class-> using Newtonsoft.Json;
  2. Parse -> string json = JsonConvert.SerializeObject (object);
0
source share

All Articles