首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >getJSONArray不工作optJSONArray返回null

getJSONArray不工作optJSONArray返回null
EN

Stack Overflow用户
提问于 2014-05-10 07:55:41
回答 5查看 3.9K关注 0票数 0

我正在尝试将JSON代码读入android应用程序。

JSON代码是:

代码语言:javascript
复制
{
 "query": {
  "count": 2,
  "created": "2014-05-07T21:08:55Z",
  "lang": "en-US",
  "diagnostics": {
   "publiclyCallable": "true",
   "url": [
    {
     "execution-start-time": "1",
     "execution-stop-time": "66",
     "execution-time": "65",
     "content": "http://www.datatables.org/yahoo/finance/quote/yahoo.finance.quote.xml"
    },
    {
     "execution-start-time": "70",
     "execution-stop-time": "179",
     "execution-time": "109",
     "content": "http://download.finance.yahoo.com/d/quotes.csv?f=aa2bb2b3b4cc1c3c6c8dd1d2ee1e7e8e9ghjkg1g3g4g5g6ii5j1j3j4j5j6k1k2k4k5ll1l2l3mm2m3m4m5m6m7m8nn4opp1p2p5p6qrr1r2r5r6r7ss1s7t1t7t8vv1v7ww1w4xy&s=BBVA"
    },
    {
     "execution-start-time": "2",
     "execution-stop-time": "572",
     "execution-time": "570",
     "content": "http://www.datatables.org/yahoo/finance/yahoo.finance.xchange.xml"
    },
    {
     "execution-start-time": "576",
     "execution-stop-time": "685",
     "execution-time": "109",
     "content": "http://download.finance.yahoo.com/d/quotes.csv?s=USDEUR=X&f=snl1d1t1ab"
    }
   ],
   "cache": [
    {
     "execution-start-time": "69",
     "execution-stop-time": "69",
     "execution-time": "0",
     "method": "GET",
     "type": "MEMCACHED",
     "content": "c7570b39f80748ad6afbbe8112eb8a8d"
    },
    {
     "execution-start-time": "576",
     "execution-stop-time": "576",
     "execution-time": "0",
     "method": "GET",
     "type": "MEMCACHED",
     "content": "71eb51553e3ee73f248dfdafabda5c44"
    }
   ],
   "query": [
    {
     "execution-start-time": "70",
     "execution-stop-time": "179",
     "execution-time": "109",
     "params": "{url=[http://download.finance.yahoo.com/d/quotes.csv?f=aa2bb2b3b4cc1c3c6c8dd1d2ee1e7e8e9ghjkg1g3g4g5g6ii5j1j3j4j5j6k1k2k4k5ll1l2l3mm2m3m4m5m6m7m8nn4opp1p2p5p6qrr1r2r5r6r7ss1s7t1t7t8vv1v7ww1w4xy&s=BBVA]}",
     "content": "select * from csv where url=@url and columns='Ask,AverageDailyVolume,Bid,AskRealtime,BidRealtime,BookValue,Change&PercentChange,Change,Commission,ChangeRealtime,AfterHoursChangeRealtime,DividendShare,LastTradeDate,TradeDate,EarningsShare,ErrorIndicationreturnedforsymbolchangedinvalid,EPSEstimateCurrentYear,EPSEstimateNextYear,EPSEstimateNextQuarter,DaysLow,DaysHigh,YearLow,YearHigh,HoldingsGainPercent,AnnualizedGain,HoldingsGain,HoldingsGainPercentRealtime,HoldingsGainRealtime,MoreInfo,OrderBookRealtime,MarketCapitalization,MarketCapRealtime,EBITDA,ChangeFromYearLow,PercentChangeFromYearLow,LastTradeRealtimeWithTime,ChangePercentRealtime,ChangeFromYearHigh,PercebtChangeFromYearHigh,LastTradeWithTime,LastTradePriceOnly,HighLimit,LowLimit,DaysRange,DaysRangeRealtime,FiftydayMovingAverage,TwoHundreddayMovingAverage,ChangeFromTwoHundreddayMovingAverage,PercentChangeFromTwoHundreddayMovingAverage,ChangeFromFiftydayMovingAverage,PercentChangeFromFiftydayMovingAverage,Name,Notes,Open,PreviousClose,PricePaid,ChangeinPercent,PriceSales,PriceBook,ExDividendDate,PERatio,DividendPayDate,PERatioRealtime,PEGRatio,PriceEPSEstimateCurrentYear,PriceEPSEstimateNextYear,Symbol,SharesOwned,ShortRatio,LastTradeTime,TickerTrend,OneyrTargetPrice,Volume,HoldingsValue,HoldingsValueRealtime,YearRange,DaysValueChange,DaysValueChangeRealtime,StockExchange,DividendYield'"
    },
    {
     "execution-start-time": "1",
     "execution-stop-time": "188",
     "execution-time": "187",
     "content": "\n    select * from yahoo.finance.quote where symbol in (\"BBVA\")"
    },
    {
     "execution-start-time": "576",
     "execution-stop-time": "685",
     "execution-time": "109",
     "content": "select * from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=USDEUR=X&f=snl1d1t1ab' and columns='Symbol,Name,Rate,Date,Time,Ask,Bid'"
    },
    {
     "execution-start-time": "1",
     "execution-stop-time": "686",
     "execution-time": "685",
     "content": "\n    select * from yahoo.finance.xchange where pair=\"USDEUR\"\n"
    }
   ],
   "javascript": [
    {
     "execution-start-time": "67",
     "execution-stop-time": "187",
     "execution-time": "119",
     "instructions-used": "56918",
     "table-name": "yahoo.finance.quote"
    },
    {
     "execution-start-time": "574",
     "execution-stop-time": "685",
     "execution-time": "110",
     "instructions-used": "75584",
     "table-name": "yahoo.finance.xchange"
    }
   ],
   "user-time": "686",
   "service-time": "853",
   "build-version": "0.2.2467"
  },
  "meta": {
   "meta": [
    null,
    null
   ]
  },
  "results": {
   "results": [
    {
     "quote": {
      "symbol": "BBVA",
      "AverageDailyVolume": "1436710",
      "Change": "+0.03",
      "DaysLow": "12.18",
      "DaysHigh": "12.32",
      "YearLow": "8.13",
      "YearHigh": "13.54",
      "MarketCapitalization": "71.052B",
      "LastTradePriceOnly": "12.28",
      "DaysRange": "12.18 - 12.32",
      "Name": "Banco Bilbao Vizc",
      "Symbol": "BBVA",
      "Volume": "959802",
      "StockExchange": "NYSE"
     }
    },
    {
     "rate": {
      "id": "USDEUR",
      "Name": "USD to EUR",
      "Rate": "0.7188",
      "Date": "5/7/2014",
      "Time": "5:05pm",
      "Ask": "0.7189",
      "Bid": "0.7188"
     }
    }
   ]
  }
 }
}

android的代码是:

公共类MainActivity扩展活动{

代码语言:javascript
复制
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());

    final TextView bolsa=(TextView)findViewById(R.id.bolsa);
    String resultado=busqueda();
    bolsa.append(resultado);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
public static String busqueda()
{
    String devuelve=""; 
    HttpClient comunicacion=new DefaultHttpClient(); 

    HttpGet peticion=new HttpGet("http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20yql.query.multi%20WHERE%20queries%3D%27%0A%20%20%20%20select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20%28%22BBVA%22%29%3B%0A%20%20%20%20select%20*%20from%20yahoo.finance.xchange%20where%20pair%3D%22USDEUR%22%0A%27%3B&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&format=json");

    peticion.setHeader("content-type","application/json");



try
        {
            HttpResponse respuesta=comunicacion.execute(peticion);
            System.out.println("2");
            String respuestaCad=EntityUtils.toString(respuesta.getEntity());
            System.out.println("3");
        JSONObject respuestaJSON=new JSONObject(respuestaCad);
        System.out.println(respuestaJSON);

        JSONArray resultJSON=respuestaJSON.getJSONArray("results");
        System.out.println("4");

                    //JSONArray resultJSON=respuestaJSON.optJSONArray("results");


        String direccion="SIN DATOS";

        if(resultJSON.length()>0)
        {
            direccion=resultJSON.getJSONObject(0).getString("quote");
            System.out.println("5");
        }
        devuelve="Direccion: "+direccion;
    }

    catch(Exception e)
    {

        System.out.println("error");

    }
    return devuelve;
    }

}

我想读LastTradePriceOnly,但是getJSONArray方法不能工作(我看不到控制台中的System.out.println("4")。我看到一个例外)。我尝试过通过getJSONArray更改optJSONArray,但随后出现System.out.println("4"),然后resultJSON返回null。谢谢你的帮助。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2014-05-10 08:34:51

按照上面提供的JSON,尝试下面的代码段。以后尝试使用http://json.parser.online.fr/进行进一步的联机JSON解析。

代码语言:javascript
复制
 try {

        HttpResponse respuesta=comunicacion.execute(peticion);
        System.out.println("2");
        String respuestaCad=EntityUtils.toString(respuesta.getEntity());
        System.out.println("3");
        JSONObject respuestaJSON=new JSONObject(respuestaCad);
        System.out.println(respuestaJSON);

    JSONObject respuestaJSON = new JSONObject(respuestaCad);
    System.out.println(respuestaJSON);

    JSONObject resultJSONObject = respuestaJSON.
            getJSONObject("query").getJSONObject("results");
    JSONArray resultJSON=resultJSONObject.getJSONArray("results");
        System.out.println("4");
 String direccion="SIN DATOS";

    if(resultJSON.length()>0)
    {
        direccion=resultJSON.getJSONObject(0).getString("quote");
        System.out.println("5");
    }
    devuelve="Direccion: "+direccion;

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
票数 0
EN

Stack Overflow用户

发布于 2014-05-10 08:02:26

结果数组位于JSONObject中。

尝试:

JSONArray resultJSON=respuestaJSON.getJSONObject ("results").getJSONArray("results");

票数 0
EN

Stack Overflow用户

发布于 2014-05-10 08:09:06

像这样编辑你的代码。您必须先获得obecjct“结果”,然后才能得到“结果”数组。

代码语言:javascript
复制
    JSONObject respuestaJSON=new JSONObject(respuestaCad);
    System.out.println(respuestaJSON);
    JSONObject resultObject = respuestaJSON.getJSONObject("results");
    JSONArray resultJSON=resultObject.getJSONArray("results");
    System.out.println("4");

希望这会有所帮助:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23578570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档