java- ошибка, когда я пытаюсь конвертировать xml-ответ в pojo, используя xstream - PullRequest
0 голосов
/ 15 декабря 2011

Я получаю сообщение об ошибке для следующего кода в веб-приложении Java -

         XStream xstream = new XStream();  
         apiresponse myClassObject;
         myClassObject= xstream.fromXML(resp);  

Ошибка отображается для строки кода чуть выше этой строки-- error = "Несоответствие типов - невозможнопреобразовать из объекта в apiresponse "

Ниже приведен XML, который мне нужно проанализировать ---

<apiresponse version="1" xmlns="http://ahrefs.com/schemas/api/links/1">
 <resultset_links count="2">
  <result>
    <source_url>http://ahrefs.com/robot/</source_url>
    <destination_url>http://blog.ahrefs.com/</destination_url>
    <source_ip>50.22.24.236</source_ip>
    <source_title>Ahrefs – backlinks research tool</source_title>
    <visited>2011-08-31T07:56:53Z</visited>
    <anchor>Blog</anchor>
    <rating>257.674000</rating>
    <link_type>text</link_type>
    <is_nofollow>false</is_nofollow>
  </result>
  <result>
    <source_url>http://apps.vc/</source_url>
    <destination_url>http://ahrefs.com/robot/</destination_url>
    <source_ip>64.20.55.86</source_ip>
    <source_title>Device info</source_title>
    <visited>2011-08-27T18:59:31Z</visited>
    <anchor>http://ahrefs.com/robot/</anchor>
    <rating>209.787100</rating>
    <link_type>text</link_type>
    <is_nofollow>false</is_nofollow>
  </result>
 </resultset_links>
</apiresponse>

Я создал следующие классы Java для получения данных сверху xml ---

package com.arvindikchari.linkdatasmith.domain;

final public class apiresponse {  

  protected resultset_links rlinks;  


  public apiresponse() {

  }

  public resultset_links getRlinks()
  {
    return rlinks;
  }

  public setRlinks(resultset_links rlinks)
    {
        this.rlinks=rlinks;
    }


}  



final public class resultset_links {  

    protected List<result> indiv_result = new ArrayList<result>();

  public resultset_links() {

  }


  public List<result> getIndiv_result()
  {

    return List;
  }


  public  void setIndiv_result(List<result> indiv_result)
    {

        this.indiv_result=indiv_result;
    }

}  

final public class result {

   protected String source_url;
   protected String destination_url;
   protected String source_ip;
   protected String source_title;
   protected String visited;
   protected String anchor;
   protected String rating;
   protected String link_type;

public result() {

}

public String getSource_url()
{

return source_url;
}

public void setSource_url(String source_url)
{

this.source_url=source_url;
}

public String getDestination_url()
{

return destination_url;
}

public void setDestination_url(String destination_url)
{

this.destination_url=destination_url;
}

public String getSource_ip()
{

return source_ip;
}

public void setSource_ip(String source_ip)
{

    this.source_ip=source_ip;
}


public String getSource_title()
{

return source_title;
}

public void setSource_title(String source_title)
{

this.source_title=source_title;
}


public String getVisited()
{

return visited;
}

public void setVisited(String visited)
{

this.visited=visited;
}


public String getAnchor()
{

return anchor;
}

public void setAnchor(String anchor)
{ 

this.anchor=anchor;
}


public String getRating()
 {

return rating;
 }

public void setRating(String rating)
{ 

this.rating=rating;
}


public String getLink_type()
{

return link_type;
}

public void setLink_type(String link_type)
{

    this.link_type=link_type;
}


}

Что я здесь не так делаю?

1 Ответ

1 голос
/ 15 декабря 2011

У вас много ошибок, но одна, соответствующая вашему сообщению, заключается в том, что вы должны привести результат xstream.fromXML к объекту apiresponse ':

apiresponse result = (apiresponse)xstream.fromXML(resp);

Более того, предоставленный вами код (Javaклассы) не компилируются, есть много ошибок.

Вот некоторые улучшения:

Result.java :

@XStreamAlias("result")
public class Result {

   protected String source_url;
   protected String destination_url;
   protected String source_ip;
   protected String source_title;
   protected String visited;
   protected String anchor;
   protected String rating;
   protected String link_type;
   protected Boolean is_nofollow;

public Result() {

}

public String getSource_url()
{

return source_url;
}

public void setSource_url(String source_url)
{

this.source_url=source_url;
}

public String getDestination_url()
{

return destination_url;
}

public void setDestination_url(String destination_url)
{

this.destination_url=destination_url;
}

public String getSource_ip()
{

return source_ip;
}

public void setSource_ip(String source_ip)
{

    this.source_ip=source_ip;
}


public String getSource_title()
{

return source_title;
}

public void setSource_title(String source_title)
{

this.source_title=source_title;
}


public String getVisited()
{

return visited;
}

public void setVisited(String visited)
{

this.visited=visited;
}


public String getAnchor()
{

return anchor;
}

public void setAnchor(String anchor)
{

this.anchor=anchor;
}


public String getRating()
 {

return rating;
 }

public void setRating(String rating)
{

this.rating=rating;
}


public String getLink_type()
{

return link_type;
}

public void setLink_type(String link_type)
{

    this.link_type=link_type;
}

public Boolean getIs_nofollow() {
    return is_nofollow;
}

public void setIs_nofollow(Boolean is_nofollow) {
    this.is_nofollow = is_nofollow;
}

ResultsetLinks.java :

@XStreamAlias("resultset_links")
public class ResultsetLinks {

@XStreamImplicit(itemFieldName="result")
protected List<Result> indivResult = new ArrayList<Result>();

  public ResultsetLinks() {

  }

  public List<Result> getResult()
  {

    return indivResult;
  }


  public  void setResult(List<Result> indiv_result)
    {

        this.indivResult =indiv_result;
    }

}

ApiResponse.java :

@XStreamAlias("apiresponse")
public class ApiResponse {

@XStreamAlias("resultset_links")
protected ResultsetLinks rlinks;


public ApiResponse() {

}

public ResultsetLinks getRlinks()
{
    return rlinks;
}

public void setRlinks(ResultsetLinks rlinks)
  {
    this.rlinks=rlinks;
  }

}

И, наконец, ваш код для демонтажа XML:

    XStream xstream = new XStream();
    xstream.processAnnotations(ApiResponse.class);
    xstream.processAnnotations(ResultsetLinks.class);
    xstream.processAnnotations(Result.class);

    ApiResponse result = (ApiResponse)xstream.fromXML(resp);

Весь этот код работает нормально с Xstream 1.4.2

Постарайтесь следовать соглашению о кодировании Sun для имен ваших классов, имен атрибутов и т. Д. Используйте XstreamAliases для адаптацииИмя класса Java для имени XML.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...