在 Windows Phone 上将 JSON 反序列化为对象 C#

本文关键字:对象 反序列化 JSON Windows Phone 上将 | 更新日期: 2023-09-27 18:31:24

我正在尝试将从Web服务器接收的json数据服务反序列化为对象。到目前为止,我刚刚设置了一个 httpwebrequest,它从服务器获取 json 数据。

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":"jvcuejnj.ldmfkiftvh@wx-sts.net","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
}

在 Windows Phone 上将 JSON 反序列化为对象 C#

这样的事情应该给你正确的结果:

byte[] data = Encoding.UTF8.GetBytes(jsonString);
MemoryStream memStream = new MemoryStream(data);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Car));
Car car = (Car) serializer.ReadObject(memStream);

尽管如果要跳过 MemoryStream 部分,可以直接从响应流中反序列化

你可以

试试这个: http://json.codeplex.com/