13

在尝试在 C# 中反序列化 JSON 时,在获取信息时发现了一些困难。

我有以 JSON 格式返回的 Google 自定义搜索结果。我只想检查我的步骤并建立尝试反序列化它的顺序。这是正确的吗?

  1. 我需要创建类以匹配 JSON 格式。有点像创建模式文件。
  2. 使用JavaScriptSerializer()类和 deserialize方法提取相关位。

我认为我会遇到的问题之一是我不需要返回所有数据,而只需要 html 链接。我怎样才能做到这一点?

更新

我已使用以下 JSON 片段和 C# 代码更新了我的问题。我想将字符串“链接”输出到控制台,但它似乎不起作用。我认为我错误地定义了我的课程?

来自 Google 自定义搜索的 JSON

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=My Key&cx=My CX&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();
    }
}

谢谢

4

3 回答 3

12

我使用您的#2 方法:使用JavaScriptSerializer反序列化。

这就是我反序列化来自 Facebook 的响应的方法:

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

....Facebook.Data.Resource 的定义如下:

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

responseText我正在反序列化看起来像这样:

{"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",
 ...

但是由于我在Resource类中只定义了一个属性,所以我只反序列化. 在类中定义要反序列化的字段。

当然,它可以使用继承。您可以像这样定义数据类:

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

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

}

...然后您可以反序列化一个Person对象。


编辑

好的,鉴于您在更新的问题中提供的示例 json,以下是我编写类来保存响应的方式:

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# 代码:

    // 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 类中的第一个属性是kind,对应于 json 对象中的第一个命名属性。你有linkwhich 行不通,因为link它不是该 json 对象中顶级属性的名称。在您的 json 的层次结构中有一些名为“link”的属性较低,但 JavaScriptSerializer 不会将那些较低级别的东西拉到较高级别。
  • 我的 GoogleSearchResults 类中的下一个属性是 SourceUrl 类型。这是因为urljson 中的属性不是一个简单的字符串——它是一个带有两个属性的 json 对象,每个属性都有一个字符串值。因此 SourceUrl 作为 C# 中的一个类获得两个字符串属性,每个属性都有适当的名称来反序列化这些命名属性之一。
  • GoogleSearchResults 类中的下一个属性称为“items”,以便它可以从您的 json 中反序列化项目字典。现在 items,顾名思义,是 json 中的一个数组,由其值周围的方括号表示。这意味着可以有多个项目,尽管在您的情况下只有一个项目。所以 C# 中的这个属性必须是一个数组(或集合)。json 结果中的每个项目都不是一个简单的字符串,因此,再次,就像我们对 SourceUrl 所做的那样,我们需要定义一个持有者类来反序列化项目对象GoogleSearchItem:这个类有一堆简单的字符串属性。如果 json 需要,C# 类中的属性也可以是 int 类型或其他类型。
  • 最后,当打印出结果时,如果您只是调用Console.WriteLine(result),您将看到由 .ToString()隐式调用的方法的结果Console.WriteLine。这只会打印类型的名称,在这种情况下是“GoogleSearchResults”,我认为这不是你想要的。为了查看对象中的内容,您需要对其进行序列化,如我所展示的。在其输出中,您只会看到反序列化的事物的值。使用我提供的类,结果信息会比原来的少,因为我没有在 C# 类中提供与某些 json 属性对应的属性,所以没有反序列化。
于 2010-12-23T23:59:00.260 回答
4

您可以查看Json.NET及其对创建和查询 JSON的LINQ支持。通过制作一个漂亮的 LINQ 查询,您将只获得您需要的东西(您可以选择、分组、计数、最小值、最大值,无论您喜欢什么)。

于 2010-12-23T18:03:02.977 回答
0

http://msdn.microsoft.com/en-us/library/bb412170.aspx

http://msdn.microsoft.com/en-us/library/bb410770.aspx

将 JSON 表示形式转换为 C# 应用程序中的类型后,取出所需的属性。我不认为有一种方法可以在转换之前从 JSON 表示中仅提取一个属性(尽管我不确定)。

于 2010-12-23T18:08:19.770 回答