SORU
31 Temmuz 2009, Cuma


C ayrıştırma JSON#

Google AJAX Search API bazı JSON veri ayrıştırmak için çalışıyorum. this URL var ve sonuçlar görüntülenir, böylece yıkmak istiyorum. Şu anda bu kod yazdım, ama basit JSON dizeleri ile örnek bir dizi var, ancak bundan sonra ne yapılması gerektiği konusunda kaybetmiş gibiyim.

C yeni olmak# ve .Genel olarak NET ASP.NET benim sayfa için orijinal bir metin çıktısı almak için mücadele ettik json.net bir denemek için tavsiye ettim. Herkes sadece Google AJAX Search API JSON ve baskı almak için biraz kod yazmak için doğru yönde bana gelin bu ekran için olabilir mi?


DÜZENLEME:TÜM SABİT! Tüm sonuçları iyi çalışıyor. Yine Dreas Grech teşekkür ederiz!

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

Kod şu anda ve mükemmel bir şekilde çalışır derler, ama herhangi bir sonuç dönmüyor. Birine ihtiyacım var ne dönen, bana, sonuçları ekrana yazdırmak için hazır yardımcı olabilir mi?

Düzenleme:

Json.NET aynı JSON ve sınıfları kullanarak yukarıdaki örnek gibi çalışır.

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

Link: Serializing and Deserializing JSON with Json.NET

İlgili

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

CEVAP
2 AĞUSTOS 2009, Pazar


[Güncelleme]Deserialize yöntem eksik bir satır var. Sizin için sonuçları obj ata unutmak olmuştur

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

Ayrıca, sadece referans için, burada Serialize yöntemi :

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

Eğer json.net burada kullanmak isterseniz eşdeğer Hale/.. yukarıdaki kod için yöntemler Serisini

Serisi:

JsonConvert.DeserializeObject<T>(string json);

Seri hale getirmek:

JsonConvert.SerializeObject(object o);

Bu zaten json.net bir parçası sadece JsonConvert sınıf onları arayabilirsiniz.

Link: Serializing and Deserializing JSON with Json.NET


Properties senin yüzünden.

Örneğin bu bir :

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

getter gerçek malları iade edin (yani özelliğin getter tekrar tekrar kendini çağırıyor), ve böylece sonsuz özyineleme oluşturuyorsunuz.


Özellikler (2.0) bu gibi tanımlanmış olmalıdır :

string _unescapedUrl; // <= private field

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

Özel bir alan varsa ve alıcı bu alan değerini döndürür ve belirleyici olan alan değerini ayarlayın.


Eğer 3.5 Çerçeve kullanıyorsanız Btw, sadece bunu yapmak ve destek alanları önlemek ve derleyici çaresine bakalım

public string unescapedUrl { get; set;}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Charles Griffin Gibson

    Charles Grif

    26 NİSAN 2006
  • kimberly p

    kimberly p

    23 Ocak 2010
  • TecNoob

    TecNoob

    15 AĞUSTOS 2013