改造 POJO 空

Posted

技术标签:

【中文标题】改造 POJO 空【英文标题】:Retrofit POJO empty 【发布时间】:2015-01-14 08:31:36 【问题描述】:

谁能看到为什么我的s.getSymbol() 错误在这段代码中返回null

json 可以正常打印到终端,并且在创建“引用”时没有运行时错误。

然而,试图访问它的成员会抛出一个空指针。

我需要在我的 POJO 中包含 JSON 的所有节点吗?例如,如果我只想要 Symbol,我是否可以只拥有该数据成员,只要它是 setter 和 getter?

谢谢

Retorfit Interface     
   public class RetrofitInterface 
       private static StockApiInterface sStockService;

       public static StockApiInterface getStockApiClient() 
           if (sStockService == null) 
                 RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint("http://query.yahooapis.com/v1/public")
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .build();
            sStockService = restAdapter.create(StockApiInterface.class);
       

    return sStockService;


     public interface StockApiInterface 
        @GET("/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20
              (\"AIB.IR\")%0A%09%09&format=json&diagnostics=false&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=")                               
                 quote listQuotes();

主活动

    quote q = RetrofitInterface.getStockApiClient().listQuotes();
    if(q.getSymbol()== null)
        System.out.println("Null");
    

JSON

"query":"count":1,"created":"2014-11-17T11:06:28Z","lang":"en-US","results":"quote":"symbol":"AIB.IR","Ask":"0.105","AverageDailyVolume":"812179","Bid":"0.103","AskRealtime":"0.105","BidRealtime":"0.103","BookValue":"0.00","Change_PercentChange":"0.00 - 0.00%","Change":"0.00","Commission":null,"Currency":"EUR","ChangeRealtime":"0.00","AfterHoursChangeRealtime":"N/A - N/A","DividendShare":"0.00","LastTradeDate":"11/17/2014","TradeDate":null,"EarningsShare":"0.00","ErrorIndicationreturnedforsymbolchangedinvalid":null,"EPSEstimateCurrentYear":"0.00","EPSEstimateNextYear":"0.00","EPSEstimateNextQuarter":"0.00","DaysLow":"0.101","DaysHigh":"0.108","YearLow":"0.075","YearHigh":"0.166","HoldingsGainPercent":"- - -","AnnualizedGain":null,"HoldingsGain":null,"HoldingsGainPercentRealtime":"N/A - N/A","HoldingsGainRealtime":null,"MoreInfo":"n","OrderBookRealtime":null,"MarketCapitalization":null,"MarketCapRealtime":null,"EBITDA":"0","ChangeFromYearLow":"+0.028","PercentChangeFromYearLow":"+37.33%","LastTradeRealtimeWithTime":"N/A - <b><img src=http://eur.i1.yimg.com/eur.yimg.com/i/eu/f/e.gif width=11 height=13 border=0>0.103</b>","ChangePercentRealtime":"N/A - 0.00%","ChangeFromYearHigh":"-0.063","PercebtChangeFromYearHigh":"-37.95%","LastTradeWithTime":"5:40am - <b>0.103</b>","LastTradePriceOnly":"0.103","HighLimit":null,"LowLimit":null,"DaysRange":"0.101 - 0.108","DaysRangeRealtime":"N/A - N/A","FiftydayMovingAverage":"0.00","TwoHundreddayMovingAverage":"0.00","ChangeFromTwoHundreddayMovingAverage":null,"PercentChangeFromTwoHundreddayMovingAverage":null,"ChangeFromFiftydayMovingAverage":null,"PercentChangeFromFiftydayMovingAverage":null,"Name":"ALLIED IRISH BANK","Notes":null,"Open":"0.101","PreviousClose":"0.103","PricePaid":null,"ChangeinPercent":"0.00%","PriceSales":null,"PriceBook":null,"ExDividendDate":null,"PERatio":null,"DividendPayDate":null,"PERatioRealtime":null,"PEGRatio":null,"PriceEPSEstimateCurrentYear":null,"PriceEPSEstimateNextYear":null,"Symbol":"AIB.IR","SharesOwned":null,"ShortRatio":null,"LastTradeTime":"5:40am","TickerTrend":"&nbsp;+++-+-&nbsp;","OneyrTargetPrice":null,"Volume":"228977","HoldingsValue":null,"HoldingsValueRealtime":null,"YearRange":"0.075 - 0.166","DaysValueChange":"- - 0.00%","DaysValueChangeRealtime":"N/A - N/A","StockExchange":"Irish","DividendYield":null,"PercentChange":"0.00%"

POJO

 public class quote 

     @Expose
     private String symbol;
     @Expose
     private String Ask;
     @Expose
     private String AverageDailyVolume;
     @Expose
     private String Bid;
     @Expose
     private String AskRealtime;
     .....
     //includes all elements and setters and getter

【问题讨论】:

为什么要使用@Expose 注解? 【参考方案1】:

http://www.jsonschema2pojo.org/ 生成了以下(缩短的)POJOS,应该是可解析的:

public class ResultWrapper 
Query query;
(...)


public class Query 

private Integer count;
private String created;
private String lang;
private Results results;

(...)


public class Results 

// you might wanna make this an array in your json and a List here
private Quote quote;
(...)



public class Quote 

private String symbol;
private String Ask;
private String AverageDailyVolume;
private String Bid;
private String AskRealtime;
private String BidRealtime;
private String BookValue;
private String ChangePercentChange;
private String Change;
private Object Commission;
private String Currency;
private String ChangeRealtime;
private String AfterHoursChangeRealtime;
private String DividendShare;
private String LastTradeDate;
private Object TradeDate;
private String EarningsShare;
private Object ErrorIndicationreturnedforsymbolchangedinvalid;
private String EPSEstimateCurrentYear;
private String EPSEstimateNextYear;
private String EPSEstimateNextQuarter;
private String DaysLow;
private String DaysHigh;
private String YearLow;
private String YearHigh;
private String HoldingsGainPercent;
private Object AnnualizedGain;
private Object HoldingsGain;
private String HoldingsGainPercentRealtime;
private Object HoldingsGainRealtime;
private String MoreInfo;
private Object OrderBookRealtime;
private Object MarketCapitalization;
private Object MarketCapRealtime;
private String EBITDA;
private String ChangeFromYearLow;
private String PercentChangeFromYearLow;
private String LastTradeRealtimeWithTime;
private String ChangePercentRealtime;
private String ChangeFromYearHigh;
private String PercebtChangeFromYearHigh;
private String LastTradeWithTime;
private String LastTradePriceOnly;
private Object HighLimit;
private Object LowLimit;
private String DaysRange;
private String DaysRangeRealtime;
private String FiftydayMovingAverage;
private String TwoHundreddayMovingAverage;
private Object ChangeFromTwoHundreddayMovingAverage;
private Object PercentChangeFromTwoHundreddayMovingAverage;
private Object ChangeFromFiftydayMovingAverage;
private Object PercentChangeFromFiftydayMovingAverage;
private String Name;
private Object Notes;
private String Open;
private String PreviousClose;
private Object PricePaid;
private String ChangeinPercent;
private Object PriceSales;
private Object PriceBook;
private Object ExDividendDate;
private Object PERatio;
private Object DividendPayDate;
private Object PERatioRealtime;
private Object PEGRatio;
private Object PriceEPSEstimateCurrentYear;
private Object PriceEPSEstimateNextYear;
private String Symbol;
private Object SharesOwned;
private Object ShortRatio;
private String LastTradeTime;
private String TickerTrend;
private Object OneyrTargetPrice;
private String Volume;
private Object HoldingsValue;
private Object HoldingsValueRealtime;
private String YearRange;
private String DaysValueChange;
private String DaysValueChangeRealtime;
private String StockExchange;
private Object DividendYield;
private String PercentChange;

(...)

然后修改你的改造界面为

public interface StockApiInterface 
        @GET("/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(\"AIB.IR\")%0A%09%09&format=json&diagnostics=false&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=")                               
                 ResultWrapper listQuotes();

您现在可以通过以下方式访问报价:

ResultWrapper result = RetrofitInterface.getStockApiClient().listQuotes();
Quote q = q.getQuery().getResults().getQuote();

【讨论】:

通过 (...) 你的意思是添加 setter 和 getter? 没错,getter 和 setter。 我向 StockApiInterface 和 MainActivity 添加了所需的修改。 嗨,弗洛里安,感谢您的回复。但是我仍然在 q.getResults().getQuote() 上得到一个空指针,你是否碰巧成功运行了代码? 你是对的,我们错过了完整查询的包装器:) 我编辑了我的答案。【参考方案2】:

我认为你需要解析这个模型:

public class query 
   int count;
   String created;
   String lang;
   Quote results;
   .
   .
   .

【讨论】:

以上是关于改造 POJO 空的主要内容,如果未能解决你的问题,请参考以下文章

使用改造将不一致的 JSON 解析为 POJO

使用改造将 json 解析为 POJO

这是在没有 get/set-ters 的情况下改造 POJO 的正确方法吗?

无法使用改造库获取数据

上传改造图像但返回空服务器响应

改造 2 - 空响应体