繁体   English   中英

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

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

我正在尝试创建一个控制台应用程序客户端,该客户端可以连接到示例api并显示其中的数据。

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

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

从架构生成的类文件很大,但是我将给出一个实例示例,我尝试获取类属性的输出。

模式中的类文件

    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;
        }
    }
}

这是我的客户班

    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();
        }

    }
}

运行后,我得到以下内容

    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 . . .

我尝试了最简单的示例(id),但这给了我一个错误。 不知道出什么问题了。 任何建议将不胜感激

@罗伯特·麦基是对的。 您正在反序列化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);
}

像这样调用: AsyncWebDeserialize().Wait()

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM