Parsing JSON data with C#

2020-01-27 03:49发布

问题:

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.

回答1:

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"
         },


回答2:

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