【发布时间】:2015-03-06 17:50:19
【问题描述】:
我在 Android 应用程序中解析来自 Rails API 的 JSON 响应时遇到问题。 我的 Android 应用程序中有相当标准的 json 解析器。当我用教程中的一些 JSON url 提供它时,它似乎工作得很好(比如这个:http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php. 但是一旦我把我的链接放在那里(我使用隧道到我的本地主机) - 它无法解析任何数据并给出
JSONException: Value of type java.lang.String cannot be converted to JSONObject
所以我相信问题出在我的服务器响应中。在浏览器中的响应看起来像
{
"items": [
{
"title": "Sometitle",
"address": "Someaddress"
},
{
"title": "Sometitle2",
"address": "Someaddress2"
}
]
}
和 json 验证器显示它是有效的。我研究了类似的问题并没有找到解决方案,我不知道可能是什么原因。有人可以提出解决方案吗?
UPD。我的实际 Android 代码:
public class JsonParser {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// make HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
然后在我的活动中:
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(ITEMS_URL);
// get the array of items
dataJsonArr = new JSONArray(json);
【问题讨论】:
-
您需要发布您尝试在应用中解析 JSON 的位置的代码。
-
“在浏览器中的响应看起来像...”:是您的 Android 设备上的浏览器还是桌面上的浏览器?
-
@Ascorbin 使用解析器代码更新
-
@Vla :在这种情况下,请再次在桌面浏览器中查看它,然后查看源代码 - 那里可能还有其他内容(例如 HTML 标签等)。
-
@Squonk 实际上它在浏览器中似乎是 html 样式的,但是为什么在线 json-validators 显示来自 url 的 json 是有效的?另一个问题是我在西里尔字母中有一些字符串,这可能是原因吗?我不确定。
标签: android ruby-on-rails json parsing