使用C#反序列化JSON [英] Deserializing JSON using C#

查看:201
本文介绍了使用C#反序列化JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查找在尝试反序列化JSON在C#中采购信息的一些困难。

Finding some difficulty in sourcing information in trying to deserialize JSON in C#.

我有一个从以JSON格式返回谷歌定制搜索结果。我只是想通过我的步骤检查并试图反序列化建立秩序。这是正确的?

I have results from Google custom search returned in JSON format. I just want to check through my steps and establish the order in trying to deserialize it. Is this right?


  1. 我需要创建类相匹配
    JSON格式。有点像
    创建模式文件。

  2. 使用的JavaScriptSerializer()类和
    反序列化法来提取
    相关位。

  1. I need to create classes to match the JSON format. Kind of like a creating schema file.
  2. Use the JavaScriptSerializer() class and deserialize method to extract the relevant bits.

有一个问题我想我会碰到的一个问题是,我不要求所有返回的数据,但只有HTML链接。我怎样才能做到这一点?

One of the issues I think I am going to run into is that I don't require all of the data returned but only the html links. How can I achieve that?

更新

我已经更新我用下面的JSON片段和C#code问题。我要输出字符串'链接'到控制台,但它似乎并不奏效。我想,我定义我的班错?

I have updated my question with the following JSON snippet and C# code. I want to output the string 'links' to console but it doesn't seem to be working. I think I am defining my classes wrongly?

这是谷歌自定义搜索的JSON

JSON from Google Custom Search

handleResponse({
 "kind": "customsearch#search",
 "url": {
  "type": "application/json",
  "template": "https://www.googleapis.com/customsearch/v1?q\u003d{searchTerms}&num\u003d{count?}&start\u003d{startIndex?}&hr\u003d{language?}&safe\u003d{safe?}&cx\u003d{cx?}&cref\u003d{cref?}&sort\u003d{sort?}&alt\u003djson"
 },
 "queries": {
  "nextPage": [
   {
    "title": "Google Custom Search - lectures",
    "totalResults": 9590000,
    "searchTerms": "lectures",
    "count": 1,
    "startIndex": 2,
    "inputEncoding": "utf8",
    "outputEncoding": "utf8",
    "cx": "017576662512468239146:omuauf_lfve"
   }
  ],
  "request": [
   {
    "title": "Google Custom Search - lectures",
    "totalResults": 9590000,
    "searchTerms": "lectures",
    "count": 1,
    "startIndex": 1,
    "inputEncoding": "utf8",
    "outputEncoding": "utf8",
    "cx": "017576662512468239146:omuauf_lfve"
   }
  ]
 },
 "context": {
  "title": "Curriculum",
  "facets": [
   [
    {
     "label": "lectures",
     "anchor": "Lectures"
    }
   ],
   [
    {
     "label": "assignments",
     "anchor": "Assignments"
    }
   ],
   [
    {
     "label": "reference",
     "anchor": "Reference"
    }
   ]
  ]
 },
 "items": [
  {
   "kind": "customsearch#result",
   "title": "EE364a: Lecture Videos",
   "htmlTitle": "EE364a: \u003cb\u003eLecture\u003c/b\u003e Videos",
   "link": "http://www.stanford.edu/class/ee364a/videos.html",
   "displayLink": "www.stanford.edu",
   "snippet": "Apr 7, 2010 ... Course materials. Lecture slides · Lecture videos (2008) · Review sessions.   Assignments. Homework · Reading. Exams. Final exam ...",
   "htmlSnippet": "Apr 7, 2010 \u003cb\u003e...\u003c/b\u003e Course materials. \u003cb\u003eLecture\u003c/b\u003e slides · \u003cb\u003eLecture\u003c/b\u003e videos (2008) · Review sessions. \u003cbr\u003e  Assignments. Homework · Reading. Exams. Final exam \u003cb\u003e...\u003c/b\u003e",
   "cacheid": "TxVqFzFZLOsJ"
  }
 ]
}
);

C#代码段

public class GoogleSearchResults
{
    public string link { get; set; }

}

public class Program
{
    static void Main(string[] args)
    {
        //input search term
        Console.WriteLine("What is your search query?:");
        string searchTerm = Console.ReadLine();

        //concantenate the strings using + symbol to make it URL friendly for google
        string searchTermFormat = searchTerm.Replace(" ", "+");

        //create a new instance of Webclient and use DownloadString method from the Webclient class to extract download html
        WebClient client = new WebClient();
        string Json = client.DownloadString("https://www.googleapis.com/customsearch/v1?key=AIzaSyAAoPQprb6aAV-AfuVjoCdErKTiJHn-4uI&cx=017576662512468239146:omuauf_lfve&q=" + searchTermFormat);

        //create a new instance of JavaScriptSerializer and deserialise the desired content
        JavaScriptSerializer js = new JavaScriptSerializer();
        GoogleSearchResults results = js.Deserialize<GoogleSearchResults>(Json);

        Console.WriteLine(results);
        //Console.WriteLine(htmlDoc);
        Console.ReadLine();
    }
}

感谢

推荐答案

我用你的#2的方法:用反序列化<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\">JavaScriptSerializer.

I use your #2 approach: deserialize with the JavaScriptSerializer.

这是我做的反序列化从Facebook的响应:

This is what I do to deserialize a response from Facebook:

// get the id for the uploaded photo
var jss = new JavaScriptSerializer();
var resource = jss.Deserialize<Facebook.Data.Resource>(responseText);

....在这里Facebook.Data.Resource的定义是这样的:

....where Facebook.Data.Resource is defined like this:

namespace Facebook.Data
{
    public class Resource
    {
        public string id { get; set; }
    }
}

的responseText ,我反序列化的的是这样的:

The responseText that I am deserializing from looks like this:

{"id":"10150111918987952",
 "from":{"name":"Someone",
     "id":"782272221"},
 "name":"uploaded from Cropper. (at 12\/15\/2010 7:06:41 AM)",
 "picture":"http:\/\/photos-f.ak.fbcdn.net\/hphotos-ak-snc4\/hs817.snc4\/69790_101501113333332_782377951_7551951_8193638_s.jpg",
 ...

但既然我已经在资源定义只有一个属性类,我只反序列化的的。定义要反序列化类的字段。

But since I have only one property defined in the Resource class, I only deserialize that. Define the fields in your class that you want to deserialize.

它的工作原理使用继承,当然。你可以这样定义你的数据类:

It works to use inheritance, of course. You can define your data classes like this:

namespace Facebook.Data
{
  public class Resource
  {
    public string id { get; set; }
  }

  public class Person : Resource
  {
    public string name { get; set; }
  }

}

...然后你可以反序列化对象。

...and then you can deserialize a Person object.

修改

好吧,给你在更新的问题提供的样本JSON,以下是我写的类来响应:

Ok, given the sample json you provided in the updated question, here's how I wrote the classes to hold the response:

public class GoogleSearchItem
{
    public string kind { get; set; }
    public string title { get; set; }
    public string link { get; set; }
    public string displayLink { get; set; }
    // and so on... add more properties here if you want
    // to deserialize them
}

public class SourceUrl
{
    public string type { get; set; }
    public string template { get; set; }
}

public class GoogleSearchResults
{
    public string kind { get; set; }
    public SourceUrl url { get; set; }
    public GoogleSearchItem[] items { get; set; }
    // and so on... add more properties here if you want to
    // deserialize them
}

和这里的C#code反序列化:

And here's the C# code to deserialize:

    // create a new instance of JavaScriptSerializer
    JavaScriptSerializer s1 = new JavaScriptSerializer();

    // deserialise the received response 
    GoogleSearchResults results = s1.Deserialize<GoogleSearchResults>(json);

    Console.WriteLine(s1.Serialize(results));

一些评论:


  • 顶层类来保存搜索结果称为GoogleSearchResults。

  • 在GoogleSearchResults类中的第一个属性是,对应于JSON对象中的第一个命名的属性。你有链接这是行不通的,因为链接不是一个顶级属性的名称该JSON对象。有物业在你的JSON命名为链接的层次较低,但的JavaScriptSerializer拉不开这些低级的东西到更高的水平。

  • 在我GoogleSearchResults类的下一个属性的类型SourceUrl的。这是因为在JSON的网​​址属性不是一个简单的字符串 - 这是具有两个属性,每一个字符串值的JSON对象。所以SourceUrl在C#中的类获取两个字符串的属性,每一个相应的名称来反序列化的命名属性之一。

  • 在GoogleSearchResults类中的一个属性被称为项目,以便它可以反序列化的项目从您的JSON字典。现在的项目,顾名思义,就是在JSON数组,围绕其价值的方括号所表示。这意味着可以有一个以上的项目,尽管在你的情况,只有一个项目。所以这个属性在C#中必须是一个数组(或集合)。在JSON结果每个项目不是一个简单的字符串,所以,再一次,就像我们SourceUrl一样,我们需要定义一个holder类反序列​​化的项目对象: GoogleSearchItem 。这个类有一串简单的字符串属性。在C#类属性也可以是int类型或其它类型的,如果这就是JSON的要求。

  • 最后,打印出结果的时候,如果你只需要调用 Console.WriteLine(结果)您将看到的ToString()的结果方法时隐式 Console.WriteLine 调用。这将仅仅是打印类型的名称,在这种情况下是GoogleSearchResults,这是不是你想要的,我想。为了看看有什么对象中,你需要序列化,因为我已经证明。在该输出中,您将您的反序列化的看到事物只值。使用我公司提供的类,结果会比原来少的信息,因为我没有提供相应的一些JSON属性的C#类的属性,所以那些不反序列化。

  • The toplevel class to hold the search result is called GoogleSearchResults.
  • The first property in the GoogleSearchResults class is kind, corresponding to the first named property in the json object. You had link which isn't going to work, because link is not the name of a top-level property in that json object. There are properties lower in the hierarchy of your json named "link" but JavaScriptSerializer won't pull out those lower level things into the higher level.
  • The next property in my GoogleSearchResults class is of type SourceUrl. This is because the url property in the json is not a simple string - it is a json object with two properties, each with a string value. So SourceUrl as a class in C# gets two string properties, each with the appropriate name to deserialize one of those named properties.
  • the next property in the GoogleSearchResults class is called "items" so that it can deserialize the items dictionary from your json. Now items, as the name suggests, is an array in the json, as denoted by the square bracket around its value. This means there can be more than one item, although in your case there is just one item. So this property in C# must be an array (or collection). Each item in the json result is not a simple string, so, once again, as we did with SourceUrl, we need to define a holder class to deserialize the item object: GoogleSearchItem. This class has a bunch of simple string properties. The properties in the C# class could also be of type int or some other type, if that's what the json requires.
  • finally, when printing out the result, if you just call Console.WriteLine(result) you will see the result of the ToString() method that is implicitly invoked by Console.WriteLine. This will merely print the name of the type, in this case is "GoogleSearchResults", which is not what you want, I think. In order to see what's in the object, you need to serialize it, as I've shown. In the output of that, you will see only the values of things you deserialized. Using the classes I provided, the result will have less information than the original, because I didn't provide properties in the C# class corresponding to some of the json properties, so those weren't deserialized.

这篇关于使用C#反序列化JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆