Parsing JSON data with C #

I have about 7000 lines of JSON data that I want to parse. An example of only part of it can be seen here . What I did was use WebRequest and StreamReader to put all the data in a row. (Oddly enough, all data is placed in one VERY long line). But now I want to make it out, and I'm not sure how to do it. Can anyone explain how to use Deserialize ? I have already parsed JSON data with Java, but I am having problems with C #, especially with my inability to find documentation with clear examples. Any help would be greatly appreciated.

+7
json c # visual-studio
source share
2 answers

Try JSON.Net , if you haven’t seen this, this should help you.

The Json.NET library allows you to work with JSON formatted data in .NET simple. Key features: flexible JSON serializer for quickly converting .NET classes for JSON and vice versa, and LINQ to JSON for reading and writing JSON.

A discussion of deserialization is discussed here .

The fastest way to convert between JSON text and a .NET object is using JsonSerializer. JsonSerializer converts .NET objects to their JSON equivalent and vice versa again.

The basic code structure for deserialization is below - Target still needs to be filled in to display the rest of the analyzed data elements with the appropriate type. The specified json.txt file contains your data from the above URL.

 using System; using System.IO; using Newtonsoft.Json; public class NameAndId { public string name; public int id; } public class Data { public NameAndId[] data; } public class Target { public string id; public NameAndId from; public Data likes; } public class Program { static void Main(string[] args) { string json = File.ReadAllText(@"c:\temp\json.txt"); Target newTarget = JsonConvert.DeserializeObject<Target>(json); } } 

Here is the first part of the JSON stream for reference:

 { "id": "367501354973", "from": { "name": "Bret Taylor", "id": "220439" }, "message": "Pigs run from our house in fear. Tonight, I am wrapping the pork tenderloin in bacon and putting pancetta in the corn.", "updated_time": "2010-03-06T02:57:48+0000", "likes": { "data": [ { "id": "29906278", "name": "Ross Miller" }, { "id": "732777462", "name": "Surjit Padham" }, 
+18
source share

Personally, I don’t like to transfer dependencies on external libraries when the functionality is provided by the infrastructure. In this case, the JavaScriptSerializer class:

 var serializer = new JavaScriptSerializer(); var myobj = serializer.Deserialize<MyType>(mystring); 
+9
source share

All Articles