我必须阅读这个 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
。谁能帮我?