【问题标题】:JSON GET from Itbook API来自 Itbook API 的 JSON GET
【发布时间】:2020-06-09 23:21:56
【问题描述】:

编辑:我发现这是 JArray,我需要 JObject [],但我需要一些关于如何使它成为可能的想法。

我遇到了无法从 API 获取数据的问题 - https://api.itbook.store/

尝试 url 时出错 - https://api.itbook.store/1.0/ - System.Net.WebException: '远程服务器返回错误:(404) Not Found。'

当我尝试使用此 url -https://api.itbook.store/1.0/search/mongodb 加载页面示例中的几本书时 - 我收到以下消息:Newtonsoft.Json.JsonReaderException: 'Error reading JArray from JsonReader.当前 JsonReader 项不是数组:StartObject。路径'',第 1 行,位置 1。'

    public KnjiznicaRepo()
    {

        string url = "https://api.itbook.store/1.0/";
        string json = CallRestMethod(url);

        JArray jsonObject = JArray.Parse(json);

        foreach (JObject item in jsonObject)
        {
            knjiznicas.Add(new Knjiznica
            {
                NazivKnjige = (string)item.GetValue("title"),
                Podnaziv = (string)item.GetValue("subtitle"),
                ISBN13 = (string)item.GetValue("isbn13"),
                Cijena = (string)item.GetValue("price"),
                Link = (string)item.GetValue("url")
            });
        }
    }
    public static string CallRestMethod(string url)
    {
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
        webrequest.Method = "GET";
        webrequest.ContentType = "application/x-www-form-urlencoded";
        HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
        Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
        string result = string.Empty;
        result = responseStream.ReadToEnd();
        webresponse.Close();
        return result;
    }

【问题讨论】:

    标签: c# json api get


    【解决方案1】:

    您需要使用MongoDB 图书的网址。并将输出解析为JObject 而不是JArray。然后把里面的books字段当作一个数组:

        ...
            string url = "https://api.itbook.store/1.0/search/mongodb";
            string json = CallRestMethod(url);
    
            var o = JObject.Parse(json);
    
            foreach (JObject item in o.GetValue("books"))
            {
                ...
    

    这个例子很简单,最好加上错误处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 2019-07-31
      • 2015-11-09
      • 1970-01-01
      • 2016-08-06
      • 2016-03-04
      • 2018-04-28
      • 2019-11-26
      相关资源
      最近更新 更多