【问题标题】:Consuming Api in Console Application在控制台应用程序中使用 API
【发布时间】: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\":\"STAR‌​CAR\",\"Adminlvl\":\‌​"2\",\"LvlDesc\":\"S‌​系统 Admin\"},{\"PayorCode\":\"STARCAR\",\"Adminlvl\":\"3\",\"Lvl‌​Desc\":\"系统 用户\"}]"

【问题讨论】:

  • 你能和我们分享一下 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&amp;adminlvl=1");?
  • 不,当执行该行代码时会引发异常,所以我真的不知道它得到了什么。但是当我尝试使用 var message = res.Content.ReadAsStringAsync().Result;我得到了我刚刚发布的 json 字符串:D

标签: c# json api json.net


【解决方案1】:

当您获取 JSON 数据时,请检查您获取的是单个数据还是列表数据。你得到这个Newtonsoft.Json.JsonSerializationException的原因是因为你将它映射到IndividualModel,所以它无法将你的JSON数据映射到你的模型。

我的建议是在GetAsync() 之后添加一个断点,然后检查它是否是一个列表。如果是,则更改此行:

IndividualModel tag = await res.Content.ReadAsAsync<IndividualModel>();

到这里:

List<IndividualModel> tag = await res.Content.ReadAsAsync<List<IndividualModel>>();

希望对你有帮助!

【讨论】:

  • 成功了!我的模型得到了值,但标签的值是“{ConsoneApplication1.Program.IndividualModel}”,但无论如何,谢谢先生,我会自己解决这个问题。 :D 帮了大忙!
  • 您现在应该像这样调用每个值,tag[0].etc。这是一个示例: Console.WriteLine("{0}\t{1}\t\t{2}", tag[0].Adminlvl, tag[0].LvlDesc, tag[0].PayorCode);
  • 已经在这里评论了解决方案。菲律宾同胞,也支持答案:P 真棒名字顺便说一句。哈哈哈
  • 是的,我的错误是我试图使用 tag.ForEach(Console.WriteLine); 输出它。谢谢你!
  • 我尝试过投票,哈哈“感谢您的反馈!15 岁以下的人投票”:( 伤心
猜你喜欢
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多