在 C# 中解析 JSON [英] Parse JSON in C#

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

问题描述

我正在尝试解析来自 Google AJAX 搜索 API 的一些 JSON 数据.我有这个网址我想分解它以便显示结果.我目前已经编写了这段代码,但我不知道接下来要做什么,尽管那里有许多带有简化 JSON 字符串的示例.

I'm trying to parse some JSON data from the Google AJAX Search API. I have this URL and I'd like to break it down so that the results are displayed. I've currently written this code, but I'm pretty lost in regards of what to do next, although there are a number of examples out there with simplified JSON strings.

作为 C# 和 .NET 的新手,我一直在努力为我的 ASP.NET 页面获得真正的文本输出,所以我被推荐尝试 JSON.NET.谁能指出我正确的方向,只需编写一些代码,这些代码将从 Google AJAX 搜索 API 中获取 JSON 并将其打印到屏幕上?

Being new to C# and .NET in general I've struggled to get a genuine text output for my ASP.NET page so I've been recommended to give JSON.NET a try. Could anyone point me in the right direction to just simply writing some code that'll take in JSON from the Google AJAX Search API and print it out to the screen?

全部修复!所有结果都运行良好.再次感谢 Dreas Grech!

ALL FIXED! All results are working fine. Thank you again 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?qu003dcache:bkg1gwNt8u4J:www.cheese.com"",""title"":""u003cbu003eCHEESEu003c/bu003e.COM - All about u003cbu003echeeseu003c/bu003e!."",""titleNoFormatting"":""CHEESE.COM - All about cheese!."",""content"":""u003cbu003eCheeseu003c/bu003e - everything you want to know about it. Search u003cbu003echeeseu003c/bu003e 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?qu003dcache:n9icdgMlCXIJ:en.wikipedia.org"",""title"":""u003cbu003eCheeseu003c/bu003e - Wikipedia, the free encyclopedia"",""titleNoFormatting"":""Cheese - Wikipedia, the free encyclopedia"",""content"":""u003cbu003eCheeseu003c/bu003e 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 u003cbu003e...u003c/bu003e""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.ilovecheese.com/"",""url"":""http://www.ilovecheese.com/"",""visibleUrl"":""www.ilovecheese.com"",""cacheUrl"":""http://www.google.com/search?qu003dcache:GBhRR8ytMhQJ:www.ilovecheese.com"",""title"":""I Love u003cbu003eCheeseu003c/bu003e!, Homepage"",""titleNoFormatting"":""I Love Cheese!, Homepage"",""content"":""The American Dairy Associationu0026#39;s official site includes recipes and information   on nutrition and storage of u003cbu003echeeseu003c/bu003e.""},{""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?qu003dcache:jvfWnVcSFeQJ:www.gnome.org"",""title"":""u003cbu003eCheeseu003c/bu003e"",""titleNoFormatting"":""Cheese"",""content"":""u003cbu003eCheeseu003c/bu003e 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 Googleu0026#39;s u003cbu003e...u003c/bu003e""}],""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?oeu003dutf8u0026ieu003dutf8u0026sourceu003dudsu0026startu003d0u0026hlu003den-GBu0026qu003dcheese""}}, ""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; }
    }
}

代码当前编译和运行完美,但没有返回任何结果.有人可以帮我返回我需要的东西,准备好打印到屏幕上的结果吗?

The code currently compiles and runs perfectly, but isn't returning any results. Could someone help me with returning what I require, the results ready to print out to the screen?

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

Json.NET works using the same JSON and classes as the example above.

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

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

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

推荐答案

[更新]
我刚刚意识到为什么您没有收到返回的结果……您的 Deserialize 方法中缺少一行.您忘记将结果分配给您的 obj :

[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方法:

Also, just for reference, here is the Serialize method :

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,这里有与上面代码等效的序列化/反序列化方法..

If you want to use Json.NET here are the equivalent Serialize/Deserialize methods to the code above..

反序列化:

JsonConvert.DeserializeObject<T>(string json);

序列化:

JsonConvert.SerializeObject(object o);

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

This are already part of Json.NET so you can just call them on the JsonConvert class.

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


现在,您获得 StackOverflow 的原因是您的属性.

以这个为例:

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

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

Notice that in the getter, you are returning the actual property (ie the property's getter is calling itself over and over again), and thus you are creating an infinite recursion.

属性(在 2.0 中)应该像这样定义:

Properties (in 2.0) should be defined like such :

string _unescapedUrl; // <= private field

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

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

You have a private field and then you return the value of that field in the getter, and set the value of that field in the setter.

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

Btw, if you're using the 3.5 Framework, you can just do this and avoid the backing fields, and let the compiler take care of that :

public string unescapedUrl { get; set;}

这篇关于在 C# 中解析 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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