Thursday, April 7, 2022

C# - Deserializing json responses for valid and error cases

 Often times when de serializing a JSON we can get a valid response or an error message depending on various factors, say like resource not found, etc., . In these cases the de serialization should work for both the valid and the error cases. We can accomplish that by inheriting the error class into the ValidResponse class.

System.Text.Json was introduced in .Net Core 3.0 and above. We do not have to use external libraries for it anymore.

PS - To work with JSON in .net 6 (.Net Core 3.0 and above) you would need the below directives
using System;
using System.Text.Json;

If trying to de serialize for an http call, you will also need
using System.Net.Http;

Inheriting the ErrorResponse
public class ValidResponse : ErrorResponse     {
        //public string id { get; set; }
        public string type { get; set; }
    }

ErrorResponse object
public class ErrorResponse    {
        public string id { get; set; }
        public string message { get; set; }
    }

Deserializing the json response after an http call say like GET, POST, etc.,
        var resp = JsonSerializer.Deserialize<ValidResponse>(jsonResponse);
       
        Console.WriteLine(resp.message);
        Console.WriteLine(resp.type);

No comments:

Post a Comment

Browser background color or monitor brightness

Have you been in a situation where you are almost sitting the whole day in front of your browser and going through a document and find that ...