Post到WebApi并获得结果HttpClient
本文关键字:结果 HttpClient WebApi Post | 更新日期: 2023-09-27 18:08:40
我正在尝试将post发送到我的WebApi,然后将结果反序列化到我的对象。我用Windows Phone 8.1发送邮件。如何获得对象从我的Web Api发送?
我的构造函数:
public MyTravelsPage()
{
Task getTravels = this.GetTravels();
}
internal async Task GetTravels()
{
string uri = "http://localhost:6234/api/services/app/travel/GetMyTravels";
TravelPositions travel = new TravelPositions();
travel.UserGuid = UserIdentity.UserId;
string x = JsonConvert.SerializeObject(travel);
var stringContent = "";
using (var client = new System.Net.Http.HttpClient())
{
// New code:
client.BaseAddress = new Uri(uri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpContent content = new StringContent(x, Encoding.UTF8);
var response = await client.PostAsync(uri, new StringContent(x, Encoding.UTF8, "application/json"));
var p = response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(p.Result);
}
}
In p. result我得到这个字符串:
"{'"success'":true,'"result'":{'"output'":[{'"id'":1,'"userGuid'":'"334e5955-fe89-4a49-b8ab-f0b36575bd8d'",'"where'":'"Bukowno'",'"forMoney'":false,'"money'":'"'",'"peopleCount'":1,'"driverGuid'":null,'"longitude'":-122.188606,'"latitude'":47.622482},{'"id'":2,'"userGuid'":'"334e5955-fe89-4a49-b8ab-f0b36575bd8d'",'"where'":'"Krakow'",'"forMoney'":false,'"money'":'"'",'"peopleCount'":1,'"driverGuid'":null,'"longitude'":-122.188606,'"latitude'":47.622482},{'"id'":3,'"userGuid'":'"334e5955-fe89-4a49-b8ab-f0b36575bd8d'",'"where'":'"Warszawa'",'"forMoney'":true,'"money'":'"'",'"peopleCount'":2,'"driverGuid'":null,'"longitude'":-122.188606,'"latitude'":47.622482},{'"id'":4,'"userGuid'":'"334e5955-fe89-4a49-b8ab-f0b36575bd8d'",'"where'":'"Zakopane'",'"forMoney'":false,'"money'":'"'",'"peopleCount'":1,'"driverGuid'":null,'"longitude'":-122.188606,'"latitude'":47.622482}]},'"error'":null,'"unAuthorizedRequest'":false}"
如何从这个json字符串只得到"结果"值?
不幸的是,我的最后一行:
var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(p.Result);
它没有给出字典…只有错误
关于更多信息,这是来自WebApi的对象
public class TravelOutput
{
public List<Travel> output { get; set; }
}
public class Travel
{
public int Id { get; set; }
public Guid UserGuid { get; set; }
public string Where { get; set; }
public bool ForMoney { get; set; }
public string Money { get; set; }
public int PeopleCount { get; set; }
public Guid? DriverGuid { get; set; }
public double Longitude { get; set; }
public double Latitude { get; set; }
}
需要一个根对象来反序列化
public class RootObject
{
public bool success { get; set; }
public TravelOutput result { get; set; }
public bool unAuthorizedRequest { get; set; }
}
现在可以反序列化为
var result = JsonConvert.DeserializeObject<RootObject>(p.Result);
你的列表现在是result.result.output