简体   繁体   中英

How to deserialize JSON values in C# and ASP.NET?

I need to fetch some values obtained from an web URL. The JSON is as given:

{"country":{"name":"India","State":"Raj": Count :239}, "Population": 25487}

Now i want to fetch the value of Count and Population using C#.

I have tried using JavaScriptSerializer(); But the problem is that its response time is much much slower.

Please suggest me a way to fetch the values from this JSON string.

Thanks

I personally use

https://github.com/ServiceStack/ServiceStack.Text

It's a very fast JSON serializer/deserializer.

I usually create an extension method to make the code tidier:

    public static string ToJson(this object _obj)
    {

        return JsonSerializer.SerializeToString(_obj);
    }

Edit:

A quick way to fetch those values would be to create a class of the data:

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

Then, using ServiceStack:

void SomeFunction(string _Json)
{
    var FeedResult = _Json.FromJson<CountryInformation>();
}

You can then get the values from FeedResult as such:

FeedResult.Country.name;

一种选择是使用Json.NET - http://json.codeplex.com/

I normally recommend using typed POCO's like @misterjingo suggested. However for one-off tasks you can use ServiceStack's Json Serializer to parse it dynamically like:

var json = "{\"country\":{\"name\":\"India\",\"State\":\"Raj\": \"Count\": 239}, \"Population\": 25487}";

var jsonObj = JsonObject.Parse(json);
var country = jsonObj.Object("country");

Console.WriteLine("Country Name: {0}, State: {1}, Count: {2} | Population: {3}",
    country["name"], country["State"], country["Count"], jsonObj["Population"]);

//Outputs:
//Country Name: India, State: Raj, Count: 239 | Population: 25487

Note: the JSON spec requires an object property name to be a string which is always double quoted.

ServiceStack's JsonSerializer is also the fastest Json Serializer for .NET much faster than other Json Serializers .

您还可以使用较新的DataContractJsonSerializer类来处理JSON数据。

你可以使用DataContractSerialiser(理想情况下,如果你创建了feed),如果你有一个棘手的格式错误的json字符串,使用JSON.net,因为它给你linq2json一次解析一个节点。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM