C# 使用 newtonsoft 或 restsharp 反序列化 json 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16530060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deserializing a json string with newtonsoft or restsharp
提问by Ian Vink
I have a string that comes out of a database which is in Json format.
我有一个来自 Json 格式的数据库的字符串。
I have tried to deserialize it with:
我试图反序列化它:
RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer();
var x = deserial .Deserialize<Customer>(myStringFromDB)
But the .Deserializefunction expects an IRestResponse
但该.Deserialize函数需要一个IRestResponse
Is there a way to use RestSharp to just deserialize raw strings?
有没有办法使用 RestSharp 来反序列化原始字符串?
采纳答案by Felipe Oriani
I also have this problem, and I solved it using the Newtonsoft.Json.
我也有这个问题,我用Newtonsoft.Json.
Include the following namespaces:
包括以下命名空间:
using Newtonsoft.Json;
using RestSharp;
and try something like this:
并尝试这样的事情:
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 Tin the case is the type you need to deserialize.
在 上response.Content,您将获得原始结果,因此只需将此字符串反序列化为 json 对象。该T在的情况下,你需要反序列化的类型。
For example:
例如:
var customerDto = JsonConvert.DeserializeObject<CustomerDto>(response.Content);
回答by StevieJ81
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.
注意事项适用 - 未经过广泛测试 - 但似乎工作得很好。

