我试图使用控制台应用程序来使用我的api 我得到了一个例外。当我试图将我的JSON数据放入我的模型时,这些是以下例外:
抛出异常:' Newtonsoft.Json.JsonSerializationException'在 抛出了mscorlib.dll异常:' System.AggregateException'在 抛出mscorlib.dll异常: ' Newtonsoft.Json.JsonSerializationException'在 ConsoleApplication1.exe中
我的源代码:
class Program
{
public class IndividualModel
{
public string PayorCode { get; set; }
public string Adminlvl { get; set; }
public string LvlDesc { get; set; }
}
static void Main(string[] args)
{
HttpClient cons = new HttpClient();
cons.BaseAddress = new Uri("http://localhost:52505/");
cons.DefaultRequestHeaders.Accept.Clear();
cons.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
try
{
MyAPIGet(cons).Wait();
}
catch (AggregateException e)
{
try
{
throw e.GetBaseException();
}
catch (Exception ea)
{
//throw ea.InnerException;
Console.WriteLine(ea.ToString());
}
}
}
static async Task MyAPIGet(HttpClient cons)
{
using (cons)
{
HttpResponseMessage res = await cons.GetAsync("api/PayorPortal/GetPayorUserLevel?payorCode=STARCAR&adminlvl=1");
res.EnsureSuccessStatusCode();
if (res.IsSuccessStatusCode)
{
IndividualModel tag = await res.Content.ReadAsAsync<IndividualModel>();
Console.WriteLine("\n");
Console.WriteLine("---------------------Calling Get Operation------------------------");
Console.WriteLine("\n");
Console.WriteLine("tagId tagName tagDescription");
Console.WriteLine("-----------------------------------------------------------");
Console.WriteLine("{0}\t{1}\t\t{2}", tag.Adminlvl, tag.LvlDesc, tag.PayorCode);
Console.ReadLine();
}
}
}
}
}
这是json数据
&#34; [{\&#34; PayorCode \&#34;:\&#34; STARCAR \&#34; \&#34; Adminlvl \&#34;:\&#34; 1 \&#34; \&#34; LvlDesc \&#34;:\&#34;管理员\&#34;},{\&#34; PayorCode \&#34;:\ &#34; STAR CAR \&#34; \&#34; Adminlvl \&#34;:\&#34; 2 \&#34; \&#34; LvlDesc \&#34; :\&#34;变体系 管理员\&#34;},{\&#34; PayorCode \&#34;:\&#34; STARCAR \&#34; \&#34; Adminlvl \&#34;:\&#34; 3 \&#34; \&#34;拉特说明\&#34;:\&#34;系统 用户\&#34;}]&#34;
答案 0 :(得分:0)
当您获得JSON数据时,请检查您是获得单个数据还是列表。您收到此Newtonsoft.Json.JsonSerializationException
的原因是因为您将JSON数据映射到模型,因为您将其映射到IndividualModel
。
我的建议是在GetAsync()
之后添加一个断点,然后检查它是否为List。如果是,则更改此行:
IndividualModel tag = await res.Content.ReadAsAsync<IndividualModel>();
到此:
List<IndividualModel> tag = await res.Content.ReadAsAsync<List<IndividualModel>>();
希望它有所帮助!