我正在开发Visual Studio 2010中的Windows Phone 7.1项目。我正在尝试下载JSON数据并将其反序列化为对象列表。以下是我用来构建Web请求和处理响应的代码。
public class HttpGetTask<T>
{
public HttpGetTask(string url, Action<T> onPostExecute)
{
this.Url = url;
this.OnPostExecute = onPostExecute;
}
public void Execute()
{
MessageBox.Show("We are in the task Execute method");
if (this.OnPreExecute != null)
{
this.OnPreExecute();
}
// create the http request
HttpWebRequest httpWebRequest = WebRequest.CreateHttp(this.Url);
httpWebRequest.Method = "GET";
httpWebRequest.Accept = "application/json";
// get the response asynchronously
httpWebRequest.BeginGetResponse(OnGetResponseCompleted, httpWebRequest);
}
private void OnGetResponseCompleted(IAsyncResult ar)
{
MessageBox.Show("We are in the OnGetResponseCompleted Method");
var httpWebRequest = (HttpWebRequest)ar.AsyncState;
// get the response
HttpWebResponse response;
try
{
response = (HttpWebResponse)httpWebRequest.EndGetResponse(ar);
}
catch (WebException e)
{
this.InvokeOnErrorHandler("Unable to connect to the web page.");
return;
}
catch (Exception e)
{
this.InvokeOnErrorHandler(e.Message);
return;
}
if (response.StatusCode != HttpStatusCode.OK)
{
this.InvokeOnErrorHandler((int)response.StatusCode + " " + response.StatusDescription);
return;
}
// response stream
var stream = response.GetResponseStream();
// deserialize json
var jsonSerializer = new DataContractJsonSerializer(typeof(T));
var responseObject = (T)jsonSerializer.ReadObject(stream);
// call the virtual method
this.InvokeInUiThread(() => this.OnPostExecute(responseObject));
}
以下是我正在使用的DataContract类。
[DataContract]
public class OwnersList
{
public List<Owner> Owners {get; set; }
}
[DataContract]
public class Owner
{
[DataMember(Name = "oid")]
public string Oid { get; set; }
[DataMember(Name = "fname")]
public string Fname { get; set; }
[DataMember(Name = "lname")]
public string Lname { get; set; }
}
以下是我试图反序列化的te JSON数据示例。
[{"oid":"1","fname":"John","lname":"Doe"},{"oid":"2","fname":"Mary","lname":"Smith"},{"oid":"3","fname":"Jimi","lname":"Hendrix"},{"oid":"4","fname":"Carole","lname":"King"},{"oid":"5","fname":"John","lname":"Winchester"},{"oid":"6","fname":"John","lname":"Hurt"},{"oid":"7","fname":"Rick","lname":"Grimes"},{"oid":"8","fname":"Haris","lname":"Okic"},{"oid":"9","fname":"Dino ","lname":"Okic"},{"oid":"10","fname":"Mirza","lname":"Cirkic"}]
当我运行我的应用程序时,无论是在创建序列化程序对象时,还是在jsonserializer.ReadObject(stream)行上,我都会收到Invalid Casting Exception。关于为什么会发生这种情况的任何想法?
答案 0 :(得分:0)
尝试使用int:
指定属性[DataMember(Name = "oid")]
public string Oid { get; set; }
应该是
[DataMember(Name = "oid")]
public int Oid { get; set; }