我正在try 解析来自Google Ajax search API的一些JSON数据.我有this URL个,我想把它细分一下,这样就可以显示结果了.我目前已经编写了这段代码,但是我不知道下一步要做什么,尽管有很多使用简化JSON字符串的示例.

总的来说,作为C#和.NET的新手,我很难为我的ASP.NET页面获得真正的文本输出,所以有人建议我try 一下JSON.NET.有人能告诉我正确的方向吗?简单地编写一些代码,这些代码将从Google Ajax search API接收JSON并将其打印到屏幕上.


EDIT:个都修好了!所有结果都很好.再次感谢你,德雷斯·格雷奇!

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ServiceModel.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GoogleSearchResults g1 = new GoogleSearchResults();
        const string json = @"{""responseData"": {""results"":[{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.cheese.com/"",""url"":""http://www.cheese.com/"",""visibleUrl"":""www.cheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:bkg1gwNt8u4J:www.cheese.com"",""title"":""\u003cb\u003eCHEESE\u003c/b\u003e.COM - All about \u003cb\u003echeese\u003c/b\u003e!."",""titleNoFormatting"":""CHEESE.COM - All about cheese!."",""content"":""\u003cb\u003eCheese\u003c/b\u003e - everything you want to know about it. Search \u003cb\u003echeese\u003c/b\u003e by name, by types   of milk, by textures and by countries.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://en.wikipedia.org/wiki/Cheese"",""url"":""http://en.wikipedia.org/wiki/Cheese"",""visibleUrl"":""en.wikipedia.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:n9icdgMlCXIJ:en.wikipedia.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e - Wikipedia, the free encyclopedia"",""titleNoFormatting"":""Cheese - Wikipedia, the free encyclopedia"",""content"":""\u003cb\u003eCheese\u003c/b\u003e is a food consisting of proteins and fat from milk, usually the milk of   cows, buffalo, goats, or sheep. It is produced by coagulation of the milk \u003cb\u003e...\u003c/b\u003e""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.ilovecheese.com/"",""url"":""http://www.ilovecheese.com/"",""visibleUrl"":""www.ilovecheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:GBhRR8ytMhQJ:www.ilovecheese.com"",""title"":""I Love \u003cb\u003eCheese\u003c/b\u003e!, Homepage"",""titleNoFormatting"":""I Love Cheese!, Homepage"",""content"":""The American Dairy Association\u0026#39;s official site includes recipes and information   on nutrition and storage of \u003cb\u003echeese\u003c/b\u003e.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.gnome.org/projects/cheese/"",""url"":""http://www.gnome.org/projects/cheese/"",""visibleUrl"":""www.gnome.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:jvfWnVcSFeQJ:www.gnome.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e"",""titleNoFormatting"":""Cheese"",""content"":""\u003cb\u003eCheese\u003c/b\u003e uses your webcam to take photos and videos, applies fancy special effects   and lets you share the fun with others. It was written as part of Google\u0026#39;s \u003cb\u003e...\u003c/b\u003e""}],""cursor"":{""pages"":[{""start"":""0"",""label"":1},{""start"":""4"",""label"":2},{""start"":""8"",""label"":3},{""start"":""12"",""label"":4},{""start"":""16"",""label"":5},{""start"":""20"",""label"":6},{""start"":""24"",""label"":7},{""start"":""28"",""label"":8}],""estimatedResultCount"":""14400000"",""currentPageIndex"":0,""moreResultsUrl"":""http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den-GB\u0026q\u003dcheese""}}, ""responseDetails"": null, ""responseStatus"": 200}";
        g1 = JSONHelper.Deserialise<GoogleSearchResults>(json);
        Response.Write(g1.content);
    }
}

public class JSONHelper
{
    public static T Deserialise<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
        ms.Close();
        return obj;
    }
}
/// Deserialise from JSON
[Serializable]
public class GoogleSearchResults
{
    public GoogleSearchResults() { }
    public GoogleSearchResults(string _unescapedUrl, string _url, string _visibleUrl, string _cacheUrl, string _title, string _titleNoFormatting, string _content)
    {
        this.unescapedUrl = _unescapedUrl;
        this.url = _url;
        this.visibleUrl = _visibleUrl;
        this.cacheUrl = _cacheUrl;
        this.title = _title;
        this.titleNoFormatting = _titleNoFormatting;
        this.content = _content;
    }

    string _unescapedUrl;
    string _url;
    string _visibleUrl;
    string _cacheUrl;
    string _title;
    string _titleNoFormatting;
    string _content;

    [DataMember]
    public string unescapedUrl
    {
        get { return _unescapedUrl; }
        set { _unescapedUrl = value; }
    }

    [DataMember]
    public string url
    {
        get { return _url; }
        set { _url = value; }
    }

    [DataMember]
    public string visibleUrl
    {
        get { return _visibleUrl; }
        set { _visibleUrl = value; }
    }
    [DataMember]
    public string cacheUrl
    {
        get { return _cacheUrl; }
        set { _cacheUrl = value; }
    }

    [DataMember]
    public string title
    {
        get { return _title; }
        set { _title = value; }
    }

    [DataMember]
    public string titleNoFormatting
    {
        get { return _titleNoFormatting; }
        set { _titleNoFormatting = value; }
    }

    [DataMember]
    public string content
    {
        get { return _content; }
        set { _content = value; }
    }
}

代码当前编译和运行得很好,但是没有返回任何结果.有没有人能帮我把我需要的东西返回,结果准备打印到屏幕上?

Edit:

Json.NET使用与上面示例相同的JSON和类工作.

GoogleSearchResults g1 = JsonConvert.DeserializeObject<GoogleSearchResults>(json);

链接:Serializing and Deserializing JSON with Json.NET

相关的

C# - parsing json formatted data into nested hashtables
Parse JSON array

推荐答案

[Update]
I've just realized why you weren't receiving results back... you have a missing line in your Deserialize method. You were forgetting to assign the results to your obj :

public static T Deserialize<T>(string json)
{
    using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
        return (T)serializer.ReadObject(ms);
    } 
}

此外,仅供参考,以下是Serialize法:

public static string Serialize<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    using (MemoryStream ms = new MemoryStream())
    {
        serializer.WriteObject(ms, obj);
        return Encoding.Default.GetString(ms.ToArray());
    }
}

Edit

如果你想使用Json.NET以下是与上述代码等效的序列化/反序列化方法..

反序列化:

JsonConvert.DeserializeObject<T>(string json);

序列化:

JsonConvert.SerializeObject(object o);

这已经是Json的一部分了.NET,这样就可以在JsonConvert类中调用它们.

Link: 100



Now, the reason you're getting a StackOverflow is because of your Properties.

举个例子:

[DataMember]
public string unescapedUrl
{
    get { return unescapedUrl; } // <= this line is causing a Stack Overflow
    set { this.unescapedUrl = value; }
}

请注意,在getter中,您返回的是实际的属性(即属性的getter一遍又一遍地调用自己),因此您创建的是一个无限递归.


属性(在2.0中)的定义如下:

string _unescapedUrl; // <= private field

[DataMember]
public string unescapedUrl
{
    get { return _unescapedUrl; } 
    set { _unescapedUrl = value; }
}

有一个私有字段,然后在getter中返回该字段的值,并在setter中设置该字段的值.


顺便说一句,如果您使用的是3.5框架,您可以这样做,避免使用支持字段,并让编译器处理:

public string unescapedUrl { get; set;}

Asp.net相关问答推荐

Azure DevOps 构建管道正在发布旧的/缓存的构建工件

设置主键时KeyAttribute属性不起作用

如何在 ASP.NET RadioButtonList 中的项目之间添加空格

如何在运行时判断动态数据类型的类型?

你能从请求变量中确定时区吗?

jquery 1.9.0 和 modernizr 无法使用 ASP.NET Web 优化框架进行缩小

加载特定 UpdatePanel 后如何调用客户端 javascript 函数

ASP.Net Core MVC - 自定义属性的客户端验证

如何确定服务器端 C# 上的浏览​​器窗口大小

如何获取当前登录用户的角色列表

错误请求 - 无效的主机名 ASP.net Visual Studio 2015

IIS - 无法通过 ip 地址而不是 localhost 访问页面

ASP.NET 5、EF 7 和 SQLite - SQLite 错误 1:没有这样的表:博客

当用户在文本框中按 Enter 键时执行按钮单击事件

如何response.write bytearray?

为什么 C# 对于 CSC 文件会遇到此错误?

如何加密 web.config 中的一项

Page.IsPostBack 和 Page.IsCallBack 有什么区别?

.Net 上是否有 URL 验证器?

如何使用实体框架执行原始 SQL 查询而无需使用模型?