7

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.

Daisama
  • 561
  • 2
  • 6
  • 7

2 Answers2

18

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"
         },
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
  • Could you please give me an example on how to use it with the link I provided? – Daisama Nov 05 '10 at 20:37
  • @Daisama - I will take a look, but that won't be happening very quickly. – Steve Townsend Nov 05 '10 at 20:39
  • @Daisama - take a look, seems straightforward. – Steve Townsend Nov 05 '10 at 21:09
  • Wow, this is very helpful. Thank you. So for the ones with multiple entries ("likes" and "messages"), then I should just make an array of objects? – Daisama Nov 05 '10 at 21:19
  • It looks to me like "likes" and "messages" can all be treated as a struct which has one member, an array of structs (each of which is actually the same as `From`). I'll try that and repost. – Steve Townsend Nov 05 '10 at 21:23
  • @Daisama - yes that worked - see new code including decode of "likes" – Steve Townsend Nov 05 '10 at 21:28
  • The original, actual data is just like the example, but it has many of them. So all of them are inside another data[] block. So the file starts like:{ "data": [ { "id": "112...etc – Daisama Nov 05 '10 at 21:28
  • That will be OK, just define a field for each that is of type `Data` as I did with `likes`. Date and Time may need special handling but give it a go first - eg. I added `DateTime updated_time;` - this converts the input to local time by default – Steve Townsend Nov 05 '10 at 21:30
  • Alright, thank you very much! I will try to work with what I have so far. May I message you with any additional questions if I run into problems? – Daisama Nov 05 '10 at 21:36
  • Just add comments here - maybe a different question if it's something complex. I'll be online on and off over the weekend. – Steve Townsend Nov 05 '10 at 21:41
  • @Zain - I don't know but I cannot think why it would not - this is just a C# class library like any other you could use from the .Net framework – Steve Townsend Nov 08 '10 at 12:12
  • @Zain - let me know and I will update the answer with appropriate info, good luck – Steve Townsend Nov 08 '10 at 12:49
9

Personally I don't like carrying around dependencies on external libraries when the functionality is provided by the framework. In this case, the JavaScriptSerializer class:

var serializer = new JavaScriptSerializer();

var myobj = serializer.Deserialize<MyType>(mystring);
Mark
  • 11,257
  • 11
  • 61
  • 97
  • Agreed. Also, I have used the DataContractJsonSerializer class, located in the System.Runtime.Serialization.Json namespace (System.Runtime.Serialization assembly) to deserialized JSon objects: `DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T)); return (T)jsonSerializer.ReadObject(memoryStream);` – Dr. Wily's Apprentice Nov 05 '10 at 20:47
  • @Dr.Wily'sApprentice: Which reference or .net framework is needed for that, though? (edit) Ah. `System.ServiceModel.Web` apparently. – Nyerguds Aug 05 '15 at 07:22