Reputation: 239
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
Upvotes: 4
Views: 744
Reputation: 143294
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.
Upvotes: 1
Reputation: 1802
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;
Upvotes: 4
Reputation: 6653
You can either use DataContractSerialiser (ideally if you create the feed) and if you have a tricky malformed json string use JSON.net as it gives you linq2json to parse through it one node at a time.
Upvotes: 0
Reputation: 50835
You could also use the newer DataContractJsonSerializer class to work with JSON data.
Upvotes: 0