我正在尝试获取自上次检查后已添加到框(数据库)中的“最近”甜甜圈列表。我很胖,想要一些美味的noms。问题:服务器给我的JSON充满了$ id和$ refs,所以我的列表最终成为一个对象,其余为null(因为response.Content.ReadAsAsync
不处理引用)。
请帮忙。我只想要一些直接的甜甜圈对象男人。这些$ ref icing或$ id填充都没有。
我的服务器端控制器:
public class DonutController : ApiController
{
private DonutEntities db = new DonutEntities();
// GET api/PackageEvent/since/{datetime}
public IEnumerable<Donut> GetDonutsSince([FromUri] String datetime) {
List<Donut> donuts = null;
DateTime dt = DateTime.Parse(datetime);
//return db.Donuts.Where(d => d.When > dt).AsEnumerable();
String sql = @"
SELECT *
FROM Donuts
WHERE [Donuts].[When] > CAST(@datetime AS DATETIME)
";
object[] parameters = new object[] {
new SqlParameter("@datetime", DateTime.Parse(datetime).ToString(CultureInfo.InvariantCulture))
};
List<Donut> results = db.Donuts.SqlQuery(sql, parameters).ToList();
if (results.Any()) {
donuts = results;
}
return donuts.AsEnumerable();
}
}
我的客户端请求方法:
public static IEnumerable<Donut> GetDonutsSince(DateTime dt) {
HttpClient api = new HttpClient { BaseAddress = new Uri("http://localhost:55174/api/") };
api.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
String url = "Donut/since?datetime=" + dt;
HttpResponseMessage response = api.GetAsync(url).Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
// outputs the raw json with $ids and $refs
IEnumerable<Donut> donuts = response.Content.ReadAsAsync<IEnumerable<Donut>>().Result;
return donuts;
}
答案 0 :(得分:0)
事实证明,解决方案是使用Json.NET。它处理$ id和$ ref属性,并实际创建一个填充了对象的列表。
新的客户端请求方法:
public static IEnumerable<Donut> GetDonutsSince(DateTime dt) {
HttpClient api = new HttpClient { BaseAddress = new Uri("http://localhost:55174/api/") };
api.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
String url = "Donut/since?datetime=" + dt;
HttpResponseMessage response = api.GetAsync(url).Result;
String responseContent = response.Content.ReadAsStringAsync().Result;
IEnumerable<Donut> events = JsonConvert.DeserializeObject<IEnumerable<Donut>>(responseContent);
return donuts;
}