2012-10-30 232 views
0

我試圖通過包含一些JSON的隱藏文本字段將一些數據發佈到我的MVC 3控制器。我有通過字符串coursesList傳入的JSON。任何人都有一個想法,爲什麼這不起作用?反序列化C#的JSON字符串

我所做的只是將JSON字符串中的字節[]寫出來,寫入MemoryStream,並反序列化那個流 - 或者試圖。 BookCourse bc總是以null屬性結束。

這裏的東西,如JSON我會使用:

[{"coursesection":"1234","netlogon":"jsmith","label":"CRSE-1313 Generic Course Titling ~ Joe Smith"}] 

而這裏的對象被反序列化爲:

using System.Runtime.Serialization; 

namespace xxxx.Models 
{ 
    [DataContract] 
    public class BookCourse 
    { 
     [DataMember] 
     public string coursesection { get; set; } 

     [DataMember] 
     public string netlogon { get; set; } 

     [DataMember] 
     public string label { get; set; } 
    } 
} 

最後,控制器動作的代碼來做到這一點 -

var byteArray = Encoding.ASCII.GetBytes(coursesList); 

// Deserialize byte array to data type 
var stream = new MemoryStream(); 
stream.Write(byteArray, 0, byteArray.Length); 
var crs = new DataContractJsonSerializer(typeof(BookCourse)); 
stream.Position = 0; 

// Read stream to object 
ad.CourseSectionIDs = new List<int>(); 
try 
{ 
    var bc = (BookCourse) crs.ReadObject(stream); 
    while (bc.coursesection != null) 
    { 
     cs.AssociateCourseBook(bc.netlogon, bc.coursesection, ad.ISBN); 
     bc = (BookCourse)crs.ReadObject(stream); 
    } 
} 
catch (System.Runtime.Serialization.SerializationException e) 
{ 
    // Is this best practice for handling "none"? 
} 
+0

後你發送的JSON的一個樣本。 – f0x

+0

您是否已經通過調試器瞭解了發生了什麼? – markpsmith

+0

您是否通過ajax調用發佈json對象?如果是這樣,只需在動作簽名中有一個相應的參數(屬性coursesection,netlogon&label)就可以開箱即用。 – nieve

回答

1

您的JSON字符串表示BookCourse的集合,而不是一個BookCourse。因此,調整代碼:

var serializer = new DataContractJsonSerializer(typeof(BookCourse[])); 

然後:

var bookCourses = (BookCourse[])crs.ReadObject(stream); 

,或者如果你想用一個單一的BookCourse你需要改變你的JSON字符串,並拆除包裝方括號代表收集工作。

+0

非常好。先生,謝謝你。 – NargothBond

1

達林是正確的,如果你想在合同水平上做到這一點,這是變化。

[DataContract] 
public class BookCourse 
{ 
    [DataMember] 
    public string coursesection { get; set; } 

    [DataMember] 
    public string netlogon { get; set; } 

    [DataMember] 
    public string label { get; set; } 
} 

[DataContract] 
public class BookCourceCollection 
{ 
    [DataMember] 
    public List<BookCourse> Collection; 

    public static BookCourceCollection ReturnCollection(string jsonString) 
    { 
     MemoryStream ms; 
     BookCourceCollection collection; 

     using (ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) 
     { 
      DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(BookCourceCollection)); 
      collection = ser.ReadObject(ms) as BookCourceCollection; 
     } 

     return collection; 
    } 

} 

用法:

string jsonString = "Your JSON string from the front end"; 

var bookCourceObject = BookCourseCollection.ReturnCollection(jsonString); 
foreach (BookCourse bookCourse in bookCourceObject.Collection) 
{ 
    cs.AssociateCourseBook(bookCourse.netlogon, bookCourse.coursesection, bookCourse.ISBN); 
}