初学Android,照着Android基础教程敲一个利用GoogleAPI翻译各国语言的项目
运行后报的是JSONException,我也不知道JSONException是什么异常
求解释为什么会有JSONException异常
部分代码如下
- Java code
private String doTranslate(String original, String from, String to){ String result = translate.getResources().getString( R.string.translation_error); HttpURLConnection con = null; Log.d(TAG, "doTranslate(" + original + ", " + from + ", " + to + ")"); try{ // Check if task has been interrupted if(Thread.interrupted()) throw new InterruptedException(); // Build RESTful query for Google API String q = URLEncoder.encode(original, "UTF-8"); URL url = new URL( "http://ajax.googleapis.com/ajax/services/language/translate" + "?v=1.0" + "&q=" + q + "&langpair=" + from + "%7C" + to); con = (HttpURLConnection)url.openConnection(); con.setReadTimeout(10000 /* milliseconds */); con.setConnectTimeout(15000 /* milliseconds */); con.setRequestMethod("GET"); con.addRequestProperty("Referer", "http://www.pragprog.com/titles/eband3/hello-android"); con.setDoInput(true); // Start the query con.connect(); // Check if task has been interrupted if(Thread.interrupted()) throw new InterruptedException(); // Read results from the query BufferedReader reader = new BufferedReader( new InputStreamReader(con.getInputStream(), "UTF-8")); String payload = reader.readLine(); reader.close(); // Parse to get translated text JSONObject jsonObject = new JSONObject(payload); result = jsonObject.getJSONObject("responseData") .getString("translatedText") .replace("'", ".") .replace("&", "&"); // Check if task has been interrupted if(Thread.interrupted()) throw new InterruptedException(); }catch(IOException e){ Log.e(TAG, "IOException", e); } catch(JSONException e){ Log.e(TAG, "JSONException", e); } catch(InterruptedException e){ Log.d(TAG, "InterruptedException", e); result = translate.getResources().getString( R.string.translation_interrupted); } finally{ if(con != null){ con.disconnect(); } } // All done Log.d(TAG, " -> returned " + result); return result; }
------解决方案--------------------
// Parse to get translated text
JSONObject jsonObject = new JSONObject(payload);
result = jsonObject.getJSONObject("responseData")
.getString("translatedText")
.replace("'", ".")
.replace("&", "&");
你解析json数据包的过程中出现了问题,最好debug到这几行看看,还有,看看payload这个字符串,看看数据格式死否符合标准的json定义
------解决方案--------------------
这个问题比较明显了,你出错的这次,给的json包中,肯定是一次服务器没有找到对应的翻译的返回包,所以你在调用getString("translatedText").由于没有translatedText这个键值,所以出现了exception.