我需要获取一些从 web URL 获得的值。 JSON 如下所示:
{"country":{"name":"India","State":"Raj": Count :239}, "Population": 25487}
现在我想使用 C# 获取 Count 和 Population 的值。
我试过使用 JavaScriptSerializer();
但问题是它的响应时间要慢得多。
请建议我从这个 JSON 字符串中获取值的方法。
谢谢
最佳答案
我个人使用
https://github.com/ServiceStack/ServiceStack.Text
这是一个非常快速的 JSON 序列化器/反序列化器。
我通常创建一个扩展方法来使代码更整洁:
public static string ToJson(this object _obj)
{
return JsonSerializer.SerializeToString(_obj);
}
编辑:
获取这些值的一种快速方法是创建一个数据类:
public class Country
{
public string name { get; set; }
public string State { get; set; }
public int Count { get; set; }
}
public class CountryInformation
{
public Country Country { get; set; }
public int Population { get; set; }
}
然后,使用 ServiceStack:
void SomeFunction(string _Json)
{
var FeedResult = _Json.FromJson<CountryInformation>();
}
然后您可以从 FeedResult 中获取值:
FeedResult.Country.name;
关于c# - 如何在 C# 和 ASP.NET 中反序列化 JSON 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8185440/