2011-11-28 86 views
2

我正在嘗試閱讀與DataContractJsonSerializer一樣的JSON,正如我平時所做的那樣。InvalidCastException與DataContractJsonSerializer

有效的JSON如下:

{ 
"error": "false", 
"errorMsg": "Error message", 
"errorField": "", 
"time": "19:24", 
"times": [ 
    [ 
     "blank", 
     "19:35", 
     "London", 
     "direct", 
     "1", 
     "new" 
    ], 
    [ 
     "blank", 
     "20:07", 
     "Manchester", 
     "direct", 
     "1", 
     "old" 
    ] 
], 
"buses": [], 
"ferries": [], 
"updates": [] 
} 

C#

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(NRResult)); 

       using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(result1))) 
       { 
        var item = (NRResult)serializer.ReadObject(stream); 
        foreach (var item in routes.Timings) 
        { 
         NRData _item = new NRData(); 

         _item.Route = route.unknown1; 
         _item.Direction = route.time; 
         _item.Time = route.destination; 
         _item.AimedDepart = route.ontime; 
         _item.ExpectedDepart = route.unknown2; 
         _item.OpRef = route.link; 

         listBox1.Items.Add(_item); 
        } 

數據類:

[DataContract] 
public class NRResult 
{ 
    [DataMember(Name = "times")] 
    public IEnumerable<Timings> Timings{ get; set; } 
} 
[DataContract] 

public class Timings { 
    [DataMember] 
    public string unknown1 { get; set; } 
    [DataMember] 
    public string time { get; set; } 
    [DataMember] 
    public string destination { get; set; } 
    [DataMember] 
    public string ontime { get; set; } 
    [DataMember] 
    public string unknown2 { get; set; } 
    [DataMember] 
    public string link { get; set; } 
} 

我得到一個InvalidCastException在該行 var item = (NRResult)serializer.ReadObject(stream); 而且我不知道爲什麼?

+0

確保TFLBuses和NRResult具有不帶參數的公共構造函數。 – invalidusername

+0

對不起,TFLBuses應該是'定時'。改變。 –

回答

2

我認爲NRResult的聲明應該是這樣的。

[DataContract] 
public class NRResult 
{ 
    [DataMember(Name = "times")] 
    public IEnumerable<string[]> Timings { get; set; } 
} 

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(NRResult)); 
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(result1))) 
{ 
    var item = (NRResult)serializer.ReadObject(stream); 
    foreach (var route in item.Timings) 
    { 
     var _item = new{ 
       Route = route[0], 
       Time = route[1], 
       Destination = route[2], 
       AimedDepart = route[3], 
       ExpectedDepart = route[4], 
       OpRef = route[5] 
      }; 

     Console.WriteLine(_item); 
    } 
}; 
+0

是的,就是這樣。我發現這個JSON的格式與我習慣的其他格式不同,因此我不需要設置類中每個字段的名稱,因爲您已將它們取出。 –

相關問題