我是开发Windowsphone7应用程序的新手,我已经开发了一个小的WP7应用程序,我发布了json数据,发布成功后,它将返回Success消息和一个id。现在我想要获取Success消息和id 。我不知道如何获得返回数据请任何人请帮助我从这里搬回来。在这里,我发布我的代码,我发布了json。
private void SendOrder_Click(object sender, EventArgs e)
{
Double grossTotal = 0.0;
List<MenuItem> mitems = new List<MenuItem>();
foreach (var item in RestaurantApp.ViewModel.Generic.Orders)
{
grossTotal += Convert.ToDouble(item.OrderTotal.TrimStart(new char[] { '$' }));
}
DateTime MyDateTime = ((DateTime)DateToDialIn.Value).Date.Add(((DateTime)TimeToDialIn.Value).TimeOfDay);
ViewModel.RootObject root = new ViewModel.RootObject()
{
order = new ViewModel.Orders()
{
LocationId = Convert.ToInt32(RestaurantApp.ViewModel.Generic.LocationPoco.LocationId),
DeviceIdentifier = Convert.ToBase64String((byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId")),
OrderContactName = txtName.Text,
OrderContactPhone = txtPhone.Text,
OrderContactEmail = txtEmail.Text,
ShipMethod = RestaurantApp.ViewModel.Generic.ShipMethod,
PickupDate = ((DateTime)DateToDialIn.Value).Date.Add(((DateTime)TimeToDialIn.Value).TimeOfDay).ToString(),
Amount = grossTotal.ToString(),
items = returnlist(mitems)
},
};
string json = null;
WebClient client = new WebClient();
client.Headers["Content-Type"] = "application/json";
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ViewModel.RootObject));
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, root);
//stream.Flush();
json = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
}
client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted);
client.UploadStringAsync(new Uri("http://api.mybusinessapp.com/restaurant/PlaceOrder"), "POST", json);
string responce = client.ResponseHeaders.ToString();
}
void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
RestaurantApp.ViewModel.Generic.Orders = null;
RestaurantApp.ViewModel.Generic.ShipMethod = null;
NavigationService.Navigate(new Uri("/Menu.xaml?LocationGUID=" + RestaurantApp.ViewModel.Generic.LocationPoco.LocationGuid, UriKind.Relative));
}
答案 0 :(得分:0)
您可以准备一个这样的辅助方法:
public static T JsonTo<T>(this string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T jsonObject;
try
{
jsonObject = (T)ser.ReadObject(ms);
}
catch (System.Runtime.Serialization.SerializationException err)
{
ms.Close();
return default(T);
}
ms.Close();
return jsonObject;
}
假设您的结果json代表一个YourResult实例:
WebClient client = new WebClient();
client.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
{
Stream stream = e.Result;
StreamReader reader = new StreamReader(stream);
yourResult = reader.ReadToEnd().JsonTo<YourResult>();
};
client.OpenReadAsync(new Uri("http://your_api"));