我正在尝试将JSON代码读取到Android应用程序。
代码JSON是:
{
"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扩展了Activity {
@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”)。我看到一个异常)。我尝试通过optJSONArray更改getJSONArray,但随后出现System.out.println(“4”),然后resultJSON返回null。谢谢你的帮助。
答案 0 :(得分:0)
resultsarray位于JSONObject内。
尝试:
JSONArray resultJSON=respuestaJSON.getJSONObject ("results").getJSONArray("results");
答案 1 :(得分:0)
像这样编辑你的代码。你必须得到结果"结果"首先,只有你能得到"结果"阵列。
JSONObject respuestaJSON=new JSONObject(respuestaCad);
System.out.println(respuestaJSON);
JSONObject resultObject = respuestaJSON.getJSONObject("results");
JSONArray resultJSON=resultObject.getJSONArray("results");
System.out.println("4");
希望这会有所帮助:)
答案 2 :(得分:0)
根据您在上面提供的JSON,尝试此代码段。 请稍后尝试http://json.parser.online.fr/进行进一步的在线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);
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();
}
答案 3 :(得分:0)
尝试替换此代码:
JSONArray resultJSON=respuestaJSON.getJSONArray("results");
System.out.println("4");
有了这个:
JSONArray resultJSON=respuestaJSON.getJSONObject("results").getJSONArray("results");
System.out.println("4");
答案 4 :(得分:0)
谢谢大家! 最后,我已经证明了最后一个代码并且它运行了。正如我想要的数据LastTradePriceOnly我改变了一点代码。
我把代码放在将来帮助某人:
公共类MainActivity扩展了Activity {
@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);
JSONObject resultJSONObject = respuestaJSON.getJSONObject("query").getJSONObject("results");
JSONArray resultJSON=resultJSONObject.getJSONArray("results");
System.out.println("4");
JSONObject direccion;
String bolsa="No datos";
if(resultJSON.length()>0)
{
direccion=resultJSON.getJSONObject(0).getJSONObject("quote");
bolsa=direccion.getString("LastTradePriceOnly");
System.out.println("5");
}
devuelve="Direccion: "+bolsa;
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return devuelve;
}
}
Pradeep Yaduvanshy,你救了我!非常感谢你:))