2012-11-27 12 views
1

我有學生類結構如下:如何使用ServiceStack.Text將文件中的數據反序列化爲自定義類JsonSerializer?

public class Student 
    { 
     public int StudentId {get;set;} 
     public string StudentName {get;set;} 
     public string[] Courses {get;set;} 
    } 

我節省了如下Student類的數據student.json文件:當我嘗試檢索數據

public void SaveStudentData(Student stud, string path) //stud is an object of student class that has student information 
    { 
     string studinfo = JsonSerializer.SerializeToString<Student>(stud); 
     StreamWriter sw = File.OpenText(path); 
     sw.Write(studinfo); 

    } 

但是,使用以下代碼:

public Student GetStudentData(string path) 
    { 
     StreamReader sr = File.OpenText(path); 
     string stud = sr.ReadToEnd(); 
     sr.Close(); 
     Student studinfo =JsonSerializer.SerializeToString<Student>(stud); 
     return studinfo; 

    } 

Student studinfo =JsonSerializer.SerializeToString<Student>(stud); 

由VS 2012高亮顯示,它不能將String類型轉換爲Student類型。我想將json數據從文件轉換爲Student類。我應該怎麼做?

+0

請參閱方法名稱**'SerializeToString' **。它返回一個字符串。應該有一種方法'DeserializeFromString' –

+0

看看這個如此回答: http://stackoverflow.com/a/7314819/937411 –

回答

2

looking here

我建議你有更多的運氣反序列化,通過調用

T JsonSerializer.DeserializeFromString<T>(string value) 

方法,而不是SerializeToString<T>這是你想要的相反。所以非一般,

Student studinfo = JsonSerializer.DeserializeFromString<Student>(stud); 

既然你是using的​​集,您可以只使用T.ToJson()string.FromJson<T>()擴展,通過@mythz評論。

+0

注意:TypeSerializer用於[JSV格式](https:// github .COM/ServiceStack/ServiceStack.Text /維基/ JSV格式)。你想要的是'JsonSerializer'或'T.ToJson()'或'string.FromJson ()'擴展方法。 – mythz

+0

@mythz,你應該知道,我會更新 – Jodrell

0

您正在使用SerializeToString從您的較早代碼返回string類型。也許你應該嘗試一種方法,將返回Student對象。

我不熟悉您使用的庫。你可以使用DataContractJsonSerializer來像這樣序列化和反序列化一個對象。

public void Save(Student student, string path) 
    { 
     FileStream fs = new FileStream(path, FileMode.OpenOrCreate); 
     DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Student)); 
     ser.WriteObject(fs, student); 
     fs.Close(); 
    } 

    public Student Load(string path) 
    { 
     FileStream fs = new FileStream(path, FileMode.Open); 
     DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Student)); 
     Student s = (Student)ser.ReadObject(fs); 
     fs.Close(); 
     return s; 
    } 

當學生對象裝飾這樣

[DataContract] 
public class Student 
{ 
    [DataMember] 
    public int StudentId { get; set; } 
    [DataMember] 
    public string StudentName { get; set; } 
    [DataMember] 
    public string[] Courses { get; set; } 
} 
相關問題