I have about 7000 lines of JSON data that I want to parse. An example of just part of it can be seen here. What I did was use WebRequest
and StreamReader
to put all the data into a string. (Oddly, it puts all of the data into one VERY long line). But now I want to parse this and I am not sure how. Can anyone explain how to use Deserialize
? I have parsed JSON data with Java before but I am having trouble doing so with C# especially with my inability to find documentation with clear examples. Any help will be greatly appreciated.
Try JSON.Net, if you have not seen this it should help you.
Json.NET library makes working with JSON formatted data in .NET simple. Key features include a flexible JSON serializer to for quickly converting .NET classes to JSON and back again, and LINQ to JSON for reading and writing JSON.
Deserialization discussed here.
The quickest method of converting between JSON text and a .NET object is using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent and back again.
The basic code structure for deserialization is below - Target
still needs to be filled out to capture the rest of the parsed data items with the appropriate type. The file mentioned json.txt
contains your data from the URL above.
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"
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With