2014-10-24 4 views
0

콘솔 응용 프로그램에서 일부 XML을 비 직렬화하려고합니다. 데이터 중 일부만 신경 쓰면 필요한 필자만으로도 수업을 만들었습니다. 프로그램이 실행되지만 내가 비 직렬화하는 PetFinderPetRecord에는 모든 빈 멤버가 있습니다 (모든 문자열은 null이고 모든 int는 0입니다). 여기 XML 비 직렬화 시도시 빈 객체가 생성됩니다.

<petfinder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://api.petfinder.com/schemas/0.9/petfinder.xsd"> 
<header> 
<version>0.1</version> 
<timestamp>2014-10-23T04:12:37Z</timestamp> 
<status> 
<code>100</code> 
<message/> 
</status> 
</header> 
<pet> 
<id>29165893</id> 
<shelterId>VA72</shelterId> 
<shelterPetId/> 
<name>Buckeye and Hawkeye</name> 
<animal>Cat</animal> 
<breeds> 
<breed>Domestic Short Hair-black</breed> 
</breeds> 
<mix>no</mix> 
<age>Baby</age> 
<sex>M</sex> 
<size>M</size> 
<options> 
<option>hasShots</option> 
<option>altered</option> 
<option>housetrained</option> 
</options> 
<description> 
<![CDATA[ 
Buckeye and Hawkeye are about 6 months old as of 5/6/14. Buckeye and his brother, Hawkeye, are very bonded and hope to find a home together. They are very playful and love to have their chin scratched. They get along very well with other cats and are curious and lovable. They will make a wonderful addition to your family. Please email [email protected] for more information. 
]]> 
</description> 
<lastUpdate>2014-05-07T21:30:42Z</lastUpdate> 
<status>A</status> 
<media> 
<photos> 
<photo id="1" size="pnt"> 
http://photos.petfinder.com/photos/pets/29165893/1/?bust=1399498241&width=60&-pnt.jpg 
</photo> 
<photo id="1" size="fpm"> 
http://photos.petfinder.com/photos/pets/29165893/1/?bust=1399498241&width=95&-fpm.jpg 
</photo> 
<photo id="1" size="x"> 
http://photos.petfinder.com/photos/pets/29165893/1/?bust=1399498241&width=500&-x.jpg 
</photo> 
<photo id="1" size="pn"> 
http://photos.petfinder.com/photos/pets/29165893/1/?bust=1399498241&width=300&-pn.jpg 
</photo> 
<photo id="1" size="t"> 
http://photos.petfinder.com/photos/pets/29165893/1/?bust=1399498241&width=50&-t.jpg 
</photo> 
<photo id="2" size="pnt"> 
http://photos.petfinder.com/photos/pets/29165893/2/?bust=1399498241&width=60&-pnt.jpg 
</photo> 
<photo id="2" size="fpm"> 
http://photos.petfinder.com/photos/pets/29165893/2/?bust=1399498241&width=95&-fpm.jpg 
</photo> 
<photo id="2" size="x"> 
http://photos.petfinder.com/photos/pets/29165893/2/?bust=1399498241&width=500&-x.jpg 
</photo> 
<photo id="2" size="pn"> 
http://photos.petfinder.com/photos/pets/29165893/2/?bust=1399498241&width=300&-pn.jpg 
</photo> 
<photo id="2" size="t"> 
http://photos.petfinder.com/photos/pets/29165893/2/?bust=1399498241&width=50&-t.jpg 
</photo> 
</photos> 
</media> 
<contact> 
<address1>PO Box 7040</address1> 
<address2/> 
<city>Fairfax Station</city> 
<state>VA</state> 
<zip>22039</zip> 
<phone>(703) 940-9183</phone> 
<fax/> 
<email>[email protected]</email> 
</contact> 
</pet> 
</petfinder> 

콘솔 코드 : 여기

은 XML입니다

public class Class1 
{ 
    static void Main(string[] args) 
    { 
     string URL = "http://api.petfinder.com/pet.getRandom"; 
     string urlParameters = "?key=myprivatekey&id=ID123&status=A&format=xml&output=full"; 

     HttpClient client = new HttpClient(); 
     client.BaseAddress = new Uri(URL); 

     client.DefaultRequestHeaders.Accept.Add(
     new MediaTypeWithQualityHeaderValue("application/xml")); 

     HttpResponseMessage response = client.GetAsync(urlParameters).Result; 
     if (response.IsSuccessStatusCode) 
     { 
      XmlRootAttribute xRoot = new XmlRootAttribute(); 
      xRoot.ElementName = "petfinder"; 
      xRoot.IsNullable = true; 
      XmlSerializer serializer = new XmlSerializer(typeof(PetFinderPetRecord), xRoot); 

      PetFinderPetRecord record = null; 

      using (Stream stream = response.Content.ReadAsStreamAsync().Result) 
      { 
       record = (PetFinderPetRecord)serializer.Deserialize(stream); // <-- has empty members 
      } 
     } 
     else 
     { 
      Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); 
     } 
    } 
} 

그리고 여기에 내가 역 직렬화하기 위해 노력하고있어 클래스에 :

[Serializable()] 
public class PetFinderPetRecord 
{ 
    [XmlElement("id")] 
    public int id { get; set; } 

    [XmlElement("shelterId")] 
    public int shelterId { get; set; } 

    [XmlElement("shelterPetId")] 
    public int shelterPetId { get; set; } 

    [XmlElement("name")] 
    public string name { get; set; } 

    [XmlElement("animal")] 
    public string animal { get; set; } 

    [XmlElement("mix")] 
    public string mix { get; set; } 

    [XmlElement("age")] 
    public string age { get; set; } 

    [XmlElement("sex")] 
    public string sex { get; set; } 

    [XmlElement("size")] 
    public string size { get; set; } 

    [XmlElement("description")] 
    public string description { get; set; } 

    [XmlElement("lastupdate")] 
    public DateTime lastupdate { get; set; } 

    [XmlElement("status")] 
    public string status; 

    public PetFinderPetRecord() 
    { 

    } 
} 

하는 경우 누군가 내가 놓친 것을 나에게 보여줄 수있었습니다. 내가 잘못하고있는 것을 보여 주면 크게 감사하게 생각합니다. 미리 감사드립니다. 이 유일한 문제이지만, 경우

+0

이 코드 예제를 수정하십시오 도움이되기를 바랍니다 (http://stackoverflow.com/help/mcve) –

+0

이를 문제를 재현하기 위해 내가 제공 할 수있는 최소한의 코드입니다. 나는 모든 XML과 내가 비 직렬화하고자하는 클래스를 완전성을 위해 제공했다. – dominicgray

+0

실제로 문제를 재현 할 수있는 코드의 양은 실제로 가능하지 않습니다. 따라서 적은 양을 제공 할 수 없다면 코드 예제를 자르는 방법을 배우는 것이 좋습니다. 또한 실제로 웹 서버를 쿼리하지 않고도 버그를 증명할 수 있다는 점을 확신 할 수 있으므로 필요한 경우보다 여기에 _more_ 코드가 있습니다. 다시, "전문 용어"로 "MCVE"를 제공하는 방법에 대해 언급 한 링크를 참조하십시오. –

답변

0

확실하지 않은 코드 줄에 : 당신이 전화 기다리고해야

  HttpResponseMessage response = client.GetAsync(urlParameters).Result; 

: 그렇지

  HttpResponseMessage response = await client.GetAsync(urlParameters).Result; 

당신의이되기 전에 문을 실행할 수있는 경우 서버 응답

참고 :이 작업을 수행하려면 메서드 선언에 async 키워드를 추가해야합니다.

static void async Main(string[] args) 

나는 이것이이 안정적으로 문제를 재현 좋은, 간결-하지만-전체 코드 예제 있도록

+0

의견을 보내 주시면 감사하겠습니다. 'async'를 진입 점에 사용할 수 없다는 오류가있어서'main'에'async'를 쓰는 대신 getData()라는 새로운 메소드를 만들었습니다. 나는 또한 당신이'HttpResponseMessage'에서 제안한 다른 변화를 만들었습니다. 이제 내가 디버깅 할 때, 그 라인 (F10)을 넘어서면 실행이 멈춘다. try catch 블록에 코드를 래핑했지만 예외가 발생하지 않습니다. 다른 제안이 있으십니까? – dominicgray

+0

나는'Task'를 리턴하기 위해'getData()'를 업데이트했고, 이제는'Main()'에서 이렇게 호출합니다 :'get(). Wait()'이 메소드는 지금 복귀하지만 객체는 여전히 비어 있습니다. 누구든지 더 이상의 제안이 있습니까? – dominicgray

+0

서버에서 어떤 응답 코드를 받고 있습니까? 코드를 xml deserialization 단계로 축소하여 질문에 제공 한 xml 파일을 deserialize하고 38 번째 줄, 68 번째 문자 (URL의 -)에 도달하면 InvalidOperation 예외가 발생했습니다. – nsyochum