此时任何建议都会受到赞赏。
我在MVC控制器中有一个简单的方法。
public IHttpActionResult GetCrudeAssessmentPrices(Int32? sellerid, DateTime? pdate, DateTime? pdateend)
{
var data = (dynamic)null;
data = db.CrudeAssessmentPrices.Select(i => new { sellerid, i.Price, i.Assessment, i.PriceDate }).Where(r => r.PriceDate >= pdate).Where(r => r.PriceDate <= pdateend).OrderBy(a => a.Assessment).ThenBy(b => b.PriceDate).ToList();
data = Json(data);
return data;
}
此方法在浏览器中的视图时返回以下内容:
[{"sellerid":95,"Price":47.14000,"Assessment":"Argus: ANS","PriceDate":"2015-10-01T00:00:00"},{"sellerid":95,"Price":49.02500,"Assessment":"Argus: ANS","PriceDate":"2015-10-01T00:00:00"}]
在控制台应用程序中,我有这个:
using System;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
namespace ConsumeJson
{
class AssessmentPrice
{
public int sellerid { get; set; }
public double Price { get; set; }
public string Assessment { get; set; }
public DateTime PriceDate { get; set; }
}
class Program
{
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:49467/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
try
{
HttpResponseMessage response = await client.GetAsync("api/CrudeAssessmentPrices?sellerid=95&pdate=10/1/2015&pdateend=10/1/2015");
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
AssessmentPrice assessmentprice = await response.Content.ReadAsAsync<AssessmentPrice>();
Console.WriteLine("{0}\t${1}\t{2}\t{3}", assessmentprice.sellerid, assessmentprice.Price, assessmentprice.Assessment, assessmentprice.PriceDate);
}
}
catch (HttpRequestException e)
{
// Handle exception.
}
}
}
}
}
运行控制台应用程序从api返回响应对象,但content属性显示标题,并且它有一个长度,但没有内容。产生以下错误:
***Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ConsumeJson.AssessmentPrice' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
Source=Newtonsoft.Json***
答案 0 :(得分:0)
您的服务正在返回一组JSON对象,但您的控制台应用程序需要一个JSON对象。您可以返回包含该数组的JSON对象:{"arrayOfObjects" : [{"one"}, {"two"}]}
或告诉它期望数组。