Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...