【发布时间】:2017-07-04 23:56:07
【问题描述】:
我正在尝试使用控制台应用程序使用我的 api,并且 我遇到了一个例外。当我尝试将我的 JSON 数据放入我的模型时,有以下例外:
抛出异常:'Newtonsoft.Json.JsonSerializationException' in mscorlib.dll 抛出异常:'System.AggregateException' in 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数据
"[{\"PayorCode\":\"STARCAR\",\"Adminlvl\":\"1\",\"LvlDesc\":\"Administrator\"},{\" PayorCode\":\"STARCAR\",\"Adminlvl\":\"2\",\"LvlDesc\":\"S系统 Admin\"},{\"PayorCode\":\"STARCAR\",\"Adminlvl\":\"3\",\"LvlDesc\":\"系统 用户\"}]"
【问题讨论】:
-
你能和我们分享一下 JSON 数据吗?那真的很有帮助。谢谢!
-
您好,这是 json 数据 "[{\"PayorCode\":\"STARCAR\",\"Adminlvl\":\"1\",\"LvlDesc\":\"管理员\"},{\"PayorCode\":\"STARCAR\",\"Adminlvl\":\"2\",\"LvlDesc\":\"系统管理员\"},{\"PayorCode\" :\"STARCAR\",\"Adminlvl\":\"3\",\"LvlDesc\":\"系统用户\"}]"
-
这是你在这行得到的:
HttpResponseMessage res = await cons.GetAsync("api/PayorPortal/GetPayorUserLevel?payorCode=STARCAR&adminlvl=1");? -
不,当执行该行代码时会引发异常,所以我真的不知道它得到了什么。但是当我尝试使用 var message = res.Content.ReadAsStringAsync().Result;我得到了我刚刚发布的 json 字符串:D