简体   繁体   English

使用ac#控制台应用程序从示例api获取数据时遇到问题

[英]Having trouble getting data from a sample api using a c# Console Application

I am trying to create a console application client that can connect to a sample api and display data from it. 我正在尝试创建一个控制台应用程序客户端,该客户端可以连接到示例api并显示其中的数据。

Schema: http://feed.elasticstats.com/schema/soccer/sr/v2/teams-standing.xsd 架构: http//feed.elasticstats.com/schema/soccer/sr/v2/teams-standing.xsd

Feed format example: http://developer.sportsdatallc.com/files/soccer_v2_standings.xml 提要格式示例: http : //developer.sportsdatallc.com/files/soccer_v2_standings.xml

The class file generated from the schema is quite large but I'll give an example of an instance I try get output for an attribute of a class. 从架构生成的类文件很大,但是我将给出一个实例示例,我尝试获取类属性的输出。

Class file from schema 模式中的类文件

    public partial class simpleTeam {

    private string idField;

    private string aliasField;

    private string nameField;

    private string country_codeField;

    private string countryField;

    private teamType typeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string id {
        get {
            return this.idField;
        }
        set {
            this.idField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string alias {
        get {
            return this.aliasField;
        }
        set {
            this.aliasField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string country_code {
        get {
            return this.country_codeField;
        }
        set {
            this.country_codeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string country {
        get {
            return this.countryField;
        }
        set {
            this.countryField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public teamType type {
        get {
            return this.typeField;
        }
        set {
            this.typeField = value;
        }
    }
}

This is my client class 这是我的客户班

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace UpdateUefaClient
{
    internal class Program
    {
        private static async Task Run()
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress =
                        new Uri("http://api.sportsdatallc.org/soccer-t2/eu/teams/standing.xml?api_key="my key to get the live feed(same as feed format)");
                        // base URL for API Controller i.e. RESTFul service

                    // add an Accept header for JSON
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // 1


                    HttpResponseMessage response = await client.GetAsync(""); // accessing the Result property blocks
                    if (response.IsSuccessStatusCode) // 200.299
                    {
                        // read result 
                        var team = await response.Content.ReadAsAsync<IEnumerable<simpleTeam>>();
                        foreach (var t in team)
                        {
                            Console.WriteLine(t.id);
                        }
                    }
                    else
                    {
                        Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase);
                    }
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

        }

        public static void Main()
        {
            Run().Wait();
        }

    }
}

After running it I get the following 运行后,我得到以下内容

    System.Runtime.Serialization.SerializationException: Error in line 1 position 12
1. Expecting element 'ArrayOfsimpleTeam' from namespace 'http://schemas.datacont
ract.org/2004/07/'.. Encountered 'Element'  with name 'standings', namespace 'ht
tp://feed.elasticstats.com/schema/soccer/sr/v2/teams-standing.xsd'.
   at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(Xml
ReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataCo
ntractResolver)
   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleException
s(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver data
ContractResolver)
   at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlReader r
eader)
   at System.Net.Http.Formatting.XmlMediaTypeFormatter.<>c__DisplayClass3.<ReadF
romStreamAsync>b__2()
   at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func,
CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at UpdateUefaClient.Program.<Run>d__0.MoveNext() in c:\Users\Daniel\Documents
\Visual Studio 2013\Projects\UpdateUefaClient\UpdateUefaClient\Program.cs:line 3
3
Press any key to continue . . .

I have tried the simplest sample (id) but that gives me an error. 我尝试了最简单的示例(id),但这给了我一个错误。 Not sure what is wrong. 不知道出什么问题了。 Any suggestions would be very much appreciated 任何建议将不胜感激

@Robert McKee is right. @罗伯特·麦基是对的。 You are deserializing standings not simpleTeam . 您正在反序列化standings而不是simpleTeam

private static standings WebDeserialize()
{
  standings s = null;
  var srlz = new XmlSerializer(typeof(standings));
  //
  var uri = "http://developer.sportsdatallc.com/files/soccer_v2_standings.xml";
  var xmlReader = XmlReader.Create (uri);
  s = (standings)srlz.Deserialize(xmlReader);
  return s;
}

static async Task AsyncWebDeserialize()
{
  Task<standings> task = Task.Run<standings>(() => WebDeserialize());
  standings s = await task;
  Console.WriteLine("Cat:{0} Gen:{1}", s.categories.Length, s.generated);
}

Call this like: AsyncWebDeserialize().Wait() 像这样调用: AsyncWebDeserialize().Wait()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 C# GUI 执行 C++ 控制台应用程序时遇到问题 - Trouble executing a C++ console application from a C# GUI 在C#中使用TryParse处理数据类型时遇到麻烦 - Having trouble with data types using TryParse in C# 我无法使用mysql.data从mysql数据库中检索盐。 (C#) - I'm having trouble retrieving a salt from a mysql database using mysql.data. (c#) 从复杂的 JSON 数据 C# 查询 Linq 时遇到问题 - Having trouble with Linq query from complex JSON Data C# API 数据导入到 SQL 服务器数据库,使用用 C# 编写的控制台应用程序 - API data import into SQL Server database using console application written in C# 从C#中的控制台应用程序将数据放在Web api上时出现“不允许使用方法(状态代码为#405)” - “Method Not Allowed(#405 status code)” While Putting Data on Web api from Console Application in C# C#和JSON无法解析数据 - C# and JSON having trouble parsing data 无法使Google打印在C#应用程序中正常工作(403禁止错误) - Having trouble getting google print to work within a C# application (403 Forbidden Error) 将数据从Web应用程序提交到C#控制台应用程序 - Submitting data from a web application to C# console application 从控制台应用程序发送输入/获取输出(C#/ WinForms) - Sending input/getting output from a console application (C#/WinForms)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM