Friday, April 8, 2022

C# - Deserializing Json without the type

 Say you receive a json string response to an http call like a GET, POST, etc., and now you like to deserialize it. It is not necessary that the data type class of the response object be declared. This can be useful when doesn't know the response type. This can be achieved by using the System.Text.Json.Node directive like in the below example.

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

        var jsonResponse = @"{""id"": ""3"", ""type"": ""some text here""}";
               
        var resp_ = System.Text.Json.Nodes.JsonNode.Parse(jsonResponse);
        Console.WriteLine(resp_);
        Console.WriteLine(resp_["id"]);

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 ...