1

我必须阅读这个 JSON:

[   
    {"id":"2","code":"jne","name":"JNE"},   
    {"id":"5","code":"pcp","name":"PCP"},   
    {"id":"1","code":"pos","name":"Pos Indonesia"}, 
    {"id":"6","code":"wahana","name":"Wahana"}  
]

我试过这个:

[DataContract]
public class Ekspedisi
{
    [DataMember]
    public int id { get; set; }
    [DataMember]
    public String code { get; set; }
    [DataMember]
    public String name { get; set; }
}

和这个:

public static Ekspedisi[] res;  
string link5 = "http://www.ongkoskirim.com/api/0.2/?id=OAL66afd139a386fee6dc5a5597abd7daba&q=expedition"    
WebClient client = new WebClient(); 
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);    
client.OpenReadAsync(new Uri(link5), UriKind.Absolute);

和这个 :

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    try
    {
        var ser = new DataContractJsonSerializer(typeof(Ekspedisi));
        res = (Ekspedisi[])ser.ReadObject(e.Result);
        for (int i = 0; i < length; i++)
        {
            Debug.WriteLine(res[i].id+","+res[i].name); 
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
        Debug.WriteLine(ex.StackTrace);
    }
} 

但它总是显示invalidCastException。谁能帮我?

4

1 回答 1

2

当您反序列化 JSON 时,您使用的是 Ekspedisi 类型,即使您正在返回一个集合。如果更改这行代码:

var ser = new DataContractJsonSerializer(typeof(Ekspedisi));

var ser = new DataContractJsonSerializer(typeof(IEnumerable<Ekspedisi>));

这是您的类型的集合;你会发现你不再收到异常。

于 2012-12-07T04:59:24.010 回答