在C#中解析JSON

我正在尝试从Google

AJAX搜索API解析一些JSON数据。我有这个网址,我想将其分解,以便显示结果。我目前已经编写了这段代码,但是尽管接下来有很多使用简化的JSON字符串的示例,但是我对于下一步的工作还是很迷茫。

一般来说,对于C#和.NET还是陌生的,我一直在努力为ASP.NET页面获取真正的文本输出,因此建议尝试一下JSON.NET。有人能为我指出正确的方向,只是简单地编写一些代码,这些代码将从Google

AJAX Search API中以JSON格式输入并输出到屏幕上吗?


全部修复!所有结果都很好。再次感谢Dreas Grech!

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

}

}

该代码当前可以编译并完美运行,但不会返回任何结果。有人可以帮助我返回我需要的结果,以便将结果打印到屏幕上吗?

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

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

链接:使用Json.NET序列化和反序列化JSON

回答:

C#-将JSON格式的数据解析为嵌套的哈希表

解析JSON数组

回答:

我刚刚意识到了为什么您没有收到结果…… Deserialize方法中缺少一行。您忘记了将结果分配给您的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());

}

}


如果要使用Json.NET,则这里是与上面的代码等效的Serialize / Deserialize方法。

反序列化:

JsonConvert.DeserializeObject<T>(string json);

连载:

JsonConvert.SerializeObject(object o);

这已经是Json.NET的一部分,因此您可以在JsonConvert类上调用它们。


现在,获得StackOverflow的原因是由于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 Framework,则可以这样做并避免使用后备字段,而让编译器来处理:

public string unescapedUrl { get; set;}

以上是 在C#中解析JSON 的全部内容, 来源链接: utcz.com/qa/406590.html

回到顶部