我試圖將從Web服務器接收的json數據服務反序列化爲對象。到目前爲止,我已經建立了一個httpwebrequest,它可以從服務器獲取json的色彩數據。反序列化json以在windows phone上對象c#
public void DoHttpWebRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(onGetResponse), request);
}
public void onGetResponse (IAsyncResult asyncResult)
{
HttpWebRequest myRequest = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(asyncResult);
using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
{
string results = httpwebStreamReader.ReadToEnd();
Dispatcher.BeginInvoke(() => textBlock5.Text = results);
}
myResponse.Close();
}
這將返回以下數據。
{"BodyStyle":"Sports","ChassisNumber":19316,"Colour":"Ivory","Condition":"Showroom","Model":"Silver Wraith","Owners":[{"DateBought":"\/Date(-207269643940+0100)\/","DateSold":"\/Date(-113297981580+0100)\/","ID":651,"Owner":{"Address":null,"Decorations":null,"Email":"[email protected]","Forename":"Ismael","ID":637,"Mobile":"008547-4461","Surname":"Anderson","Telephone":"366892-9004","Title":"Mr"}}],"RegistrationNumber":"RB4107 ","Year":1909}
我該如何使用DataContractJsonSerializer將數據解析爲下面類中的對象?
public class CarOwnershipRecord {
public int? ID{ get; set; }
public DateTime? DateBought{ get; set; }
public DateTime? DateSold{ get; set; }
public Person Owner{ get; set; }
}
public class Car {
public string BodyStyle{ get; set; }
public short? ChassisNumber{ get; set; }
public string Colour{ get; set; }
public string Condition{ get; set; }
public string Model{ get; set; }
public List<CarOwnershipRecord> Owners{ get; set; }
public string RegistrationNumber{ get; set; }
public short Year{ get; set; }
}
public class CarPhoto {
public string RegistrationNumber{ get; set; }
public byte[] Photo{ get; set; }
// The Photo field contains the binary contents of an image file
}
感謝這就是我要找的。然而,在我的json數據中,我有主對象,然後是另一個定義爲'public List Owners {get;組; }'。你將如何去解析這個數據在同一個json流中? –
user1335169
2012-04-17 01:48:57
只要您將所有DTO(Car,CarOwnerShipRecord和Person)映射出來,串行器應該只需對ReadObject()的單個調用即可處理所有事情, – 2012-04-17 06:02:31