用Google的API有JSONException生成
初学Android,照着Android基础教程敲一个利用GoogleAPI翻译各国语言的项目
运行后报的是JSONException,我也不知道JSONException是什么异常
求解释为什么会有JSONException异常
部分代码如下
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; }
建议:不要直接的去读,先看看你们定的协议,应该有一个状态字,标志是否成功的。
如果成功了就去读getString("translatedText")。
如果失败了,就不要读了
[解决办法]
和国家没关系,google translate 的 api V1 已经不能用了,明显你用的V1
V2 是收费的,好像是没兆2美元,如果没记错的话
我们也是今年换得V2 后来发现其实挺便宜的