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

I need to get some values ​​derived from a web url. JSON is listed as:

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

Now I want to get the value of Count and Population using C #.

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

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

thanks

+4
source share
5 answers

I personally use

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

This is 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 get these values ​​is to create a data class:

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

Then you can get the values ​​from FeedResult as such:

FeedResult.Country.name;

+4
source

One option is to use Json.NET - http://json.codeplex.com/

+1
source

I usually recommend using typed POCO, e.g. @misterjingo. However, for one-time tasks, you can use the ServiceStack Json Serializer for dynamic analysis:

 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 specification requires that the property name of an object be a string that is always double.

ServiceStack JsonSerializer is also the fastest Json Serializer for .NET much faster than other Json serializers .

+1
source

You can also use the new DataContractJsonSerializer class to work with JSON data.

0
source

You can use a DataContractSerialiser (ideally if you are creating a feed), and if you have a complex invalid json string, use JSON.net as it gives you linq2json to parse through one node at a time.

0
source

Source: https://habr.com/ru/post/1381929/


All Articles