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.
In this article, I have explained the concept of Serialization & Deserialization of JSON object in C# with an working console application example. Serialization is an easy way to convert an object to a binary representation that can then be e.g. written to disk or sent over a wire.Serialization is used to export application data into a file.
Deserialization. In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it creates JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns custom object (BlogSites) from JSON data.
If you have JSON that you want to deserialize, and you don't have the class to deserialize it into, you have options other than manually creating the class that you need: Use JsonDocument and Utf8JsonReader directly. Use Visual Studio 2019 to automatically generate the class you need: Copy the JSON that you need to deserialize.
Use the Utf8JsonReader directly. Copy the JSON that you need to deserialize. Create a class file and delete the template code. Choose Edit > Paste Special > Paste JSON as Classes . The result is a class that you can use for your deserialization target.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With