当前位置: 动力学知识库 > 问答 > 编程问答 >

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

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

Feed format example: 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. Not sure what is wrong. Any suggestions would be very much appreciated

网友答案:

@Robert McKee is right. You are deserializing standings not 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()

分享给朋友:
您可能感兴趣的文章:
随机阅读: