我从C#桌面客户端调用我的web api。
这是我在客户端的代码:
public IEnumerable<Model.Print> Get()
{
var print = new List<Model.Print>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Shared.URL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Shared.HeaderType));
var response = client.GetAsync(route + "?" + GeneralTags.CUSTOMER_REF + "=" + new Guid().ToString()).Result;
if (response.IsSuccessStatusCode)
{
string strJson = response.Content.ReadAsStringAsync().Result;
var jObj2 = (IEnumerable<Model.Print>)JsonConvert.DeserializeObject(strJson);
}
else
{
evError(new Exception(String.Format("{0}: {1}", (int)response.StatusCode, response.ReasonPhrase)), ErrorTags.PRINT_GET);
}
}
return print;
}
但我在这一行上收到错误:
var jObj2 = (IEnumerable<Model.Print>)JsonConvert.DeserializeObject(strJson);
错误是:
'Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.IEnumerable`1[InformedWorkerServer.Model.Print]'.
strJson包含一个值:
[
{"PrintId":1,"PrintRef":"00000000-0000-0000-0000-000000000000","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"},
{"PrintId":2,"PrintRef":"39a10cee-7cb3-4ed3-aec2-293761eed96d","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"}]
我缺少什么?
答案 0 :(得分:10)
改为使用JsonConvert.DeserializeObject<T>
:
var jObj2 = JsonConvert.DeserializeObject<List<Model.Print>>(strJson);
答案 1 :(得分:1)
如果您想格式化嵌套的json结构,如下图所示。您可以在Newtonsoft.Json中使用以下格式化程序。
解决方案: var _addressDetails = JsonConvert.DeserializeObject&gt;(Convert.ToString(data.addressDetails));