Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing a json string with restsharp

I have a string that comes out of a database which is in Json format.

I have tried to deserialize it with:

RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer(); var x = deserial .Deserialize<Customer>(myStringFromDB) 

But the .Deserialize function expects an IRestResponse

Is there a way to use RestSharp to just deserialize raw strings?

like image 862
Ian Vink Avatar asked May 13 '13 19:05

Ian Vink


People also ask

Does RestSharp use Newtonsoft?

Newtonsoft. Json package is not provided by RestSharp, is marked as obsolete on NuGet, and no longer supported by its creator.

What is serializing and deserializing JSON in C#?

Json structure is made up with {}, [], comma, colon and double quotation marks and it includes the following data types: Object, Number, Boolean, String, and Array. Serialize means convert an object instance to an XML document. Deserialize means convert an XML document into an object instance.

What does JsonConvert DeserializeObject do?

DeserializeObject Method. Deserializes the JSON to a . NET object.


2 Answers

There are sereval ways to do this. A very popular library to handle json is the Newtonsoft.Json. Probably you already have it on your asp.net project but if not, you could add it from nuget.

Considering you have a response object, include the following namespaces and call the static method DeserializeObject<T> from JsonConvert class:

using Newtonsoft.Json; using RestSharp; 
return JsonConvert.DeserializeObject<T>(response.Content); 

On the response.Content, you will have the raw result, so just deserialize this string to a json object. The T in the case is the type you need to deserialize.

For example:

var customerDto = JsonConvert.DeserializeObject<CustomerDto>(response.Content); 

Update

Recently, Microsoft has added a namespace System.Text.Json which handle json format on the .Net platform. You could use it calling the JsonSerializer.Deserialize<T> static method:

using System.Text.Json; 
var customer = JsonSerializer.Deserialize<Customer>(jsonContent); 
like image 184
Felipe Oriani Avatar answered Sep 25 '22 02:09

Felipe Oriani


If you want to avoid using extra libraries, try this:

RestSharp.RestResponse response = new RestSharp.RestResponse();  response.Content = myStringFromDB;   RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer();  Customer x = deserial.Deserialize<Customer>(response); 

Caveats apply - not extensively tested - but seems to work well enough.

like image 32
StevieJ81 Avatar answered Sep 24 '22 02:09

StevieJ81