我正在尝试将帖子发送到我的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);
}
}
在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字符串中仅获取“result”值?
不幸的是,我的最后一行:
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; }
}
答案 0 :(得分:1)
您需要 root 对象来反序列化
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