使用restsharp反序列化json字符串 [英] Deserializing a json string with restsharp

查看:127
本文介绍了使用restsharp反序列化json字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自 Json 格式的数据库的字符串.

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

我试图反序列化它:

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

但是 .Deserialize 函数需要一个 IRestResponse

But the .Deserialize function expects an IRestResponse

有没有办法使用 RestSharp 来反序列化原始字符串?

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

推荐答案

有多种方法可以做到这一点.一个非常流行的处理 json 的库是 Newtonsoft.Json.可能你已经在你的 asp.net 项目中拥有它,但如果没有,你可以从 nuget 添加它.

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.

考虑到您有一个响应对象,包括以下命名空间并从 JsonConvert 类调用静态方法 DeserializeObject:

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

response.Content 上,您将获得原始结果,因此只需将此字符串反序列化为 json 对象.案例中的 T 是您需要反序列化的类型.

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.

例如:

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

更新

最近,微软添加了一个命名空间 System.Text.Json 来处理 .Net 平台上的 json 格式.您可以使用它调用 JsonSerializer.Deserialize 静态方法:

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

这篇关于使用restsharp反序列化json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆