gpt4 book ai didi

java - 帮助处理 JSON 错误和谷歌翻译 api

转载 作者:行者123 更新时间:2023-12-04 06:29:13 25 4
gpt4 key购买 nike

我目前正在解析来自 Google Translate API 的 JSON 响应。我可以毫无问题地做到这一点。看到我没有很多 XML 经验(我更像是一个 XML 人),我无法弄清楚如何在我的 JSON 解析中实现一些错误处理。我正在使用 JSON j2me 库。

这是一个成功的响应:

{"responseData": {"translatedText":"Teks te vertaal ...","detectedSourceLanguage":"en"}, "responseDetails": null, "responseStatus": 200}

这是一个不成功的回应:
{"responseData": null, "responseDetails": "could not reliably detect source language", "responseStatus": 400}

所以,如果翻译不成功,我想把“responseDetails”的值放到一个字符串中。这是我的解析代码,它目前没有正确解析 responseDetails。相反,“尝试”的“捕获”正在被捕获。
try {
JSONObject responseObject = new JSONObject(response);
if (responseObject != null) {
JSONObject responseData = responseObject
.getJSONObject("responseData");
if (responseData != null) {
String translatedText = responseData
.getString("translatedText");
Notify.alert(translatedText);
} else {
String responseDetails = responseObject
.getString("responseDetails");
Notify.alert(responseDetails);
}
}
} catch (Exception e) {
Notify.alert("Unable to translate!");
}

谁能看到我哪里出错了?

谢谢!

最佳答案

既然你说 catch 块被触发,我会通过查看抛出的异常来开始调试。您可以简单地附加您的警报字符串以包含 e.toString()。

因此,将 catch 块中的警报更改为:

Notify.alert("Unable to translate! " + e.toString());

看看抛出的实际错误是什么。

根据您的评论,是的,它看起来像是在尝试在空值上创建 JSONObject,因此嵌套另一个 try/catch 块并以这种方式相应地解析它。
try {
JSONObject responseObject = new JSONObject(response);
if (responseObject != null) {
/* Try create a new JSON object from the
* responseData object. If it fails,
* display an alert */
try {
JSONObject responseData = responseObject
.getJSONObject("responseData");

if (responseData != null) {
String translatedText = responseData
.getString("translatedText");
Notify.alert(translatedText);
}

} catch (Exception e) {
String responseDetails = responseObject
.getString("responseDetails");
Notify.alert(responseDetails);
}
}
} catch (Exception e) {
Notify.alert("Unable to translate outer block!");
}

关于java - 帮助处理 JSON 错误和谷歌翻译 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5643851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com