2008-11-20 7 views
11

मैं VS2008Express का उपयोग कर नेट 3.5SP1 में WinForms ऐप बना रहा हूं। मैं System.Web.Script.Serialization लाइब्रेरी का उपयोग कर ऑब्जेक्ट को deserialize करने की कोशिश कर रहा हूँ।जेनिक्स/जेएसओएन जावास्क्रिप्टसेरियलाइज़र सी #

त्रुटि यह है: 'jsonWinForm.Category' टाइप करें सरणी के deserialization के लिए समर्थित नहीं है।

चीयर्स!

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Web; 
using System.Net; 
using System.IO; 
using System.Web.Script.Serialization; 

namespace jsonWinForm { 
    public class Category 
    { 
     public int categoryid; 
     public string name; 
     public int serverimageid; 
     public DateTime dateuploaded; 
     public bool enabled; 
    } 

    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      using (WebClient client = new WebClient()) 
      { 
       //manipulate request headers (optional) 
       client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 
       string targetUri = "http://www.davemateer.com/ig/genius/category.php"; 

       //execute request and read response as string to console 
       using (StreamReader reader = new StreamReader(client.OpenRead(targetUri))) 
       { 
        string s = reader.ReadToEnd(); 
        textBox1.Text = s; 

        Category cat = new Category(); 
        JavaScriptSerializer serializer = new JavaScriptSerializer(); 

        // this fails with a 
        //Type 'jsonWinForm.Category' is not supported for deserialization of an array. 
        serializer.Deserialize<Category>(s); 
       } 
      } 
     } 
    } 
} 

उत्तर

10

यह आपको अपनी त्रुटि पाई बढ़िया है। यदि आप JSON serialization के लिए किसी अन्य टूल की तलाश में हैं तो आप JSON.Net आज़मा सकते हैं।

12

मैं अपने त्रुटि पाई .. होना चाहिए:

चीयर्स

JavaScriptSerializer serializer = new JavaScriptSerializer(); 

// create a generic list of categories 
List<Category> listOfCategories = new List<Category>(); 

// deserialize as a list of Categories, and put into listOfCategories 
listOfCategories = serializer.Deserialize<List<Category>>(s); 

//iterate through list and display in text box 
foreach (Category item in listOfCategories) 
{ 
    textBox2.Text += item.categoryid.ToString() + "\r\n"; 
    textBox2.Text += item.name.ToString() + "\r\n"; 
    textBox2.Text += item.serverimageid.ToString() + "\r\n"; 
    textBox2.Text += item.dateuploaded.ToString() + "\r\n"; 
    textBox2.Text += item.enabled.ToString() + "\r\n"; 
} 
+14

यदि आप इसे Deserialize के रिटर्न परिणाम के साथ प्रतिस्थापित करने जा रहे हैं तो आपको एक नई सूची () में सूचीऑफ कैटेगरीज़ सूची शुरू करने की आवश्यकता नहीं है। – bruceboughton

संबंधित मुद्दे