Android:从 Rails API 加载数据时出现 JSONException

Android: JSONException when loading data from Rails API

我在 Android 应用程序中解析来自 Rails API 的 JSON 响应时遇到问题。 我的 Android 应用程序中有相当标准的 json 解析器。当我向它提供教程中的一些 JSON url 时,它似乎工作得很好(比如这个:http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php。 但是一旦我把我的 link 放在那里(我使用隧道到我的本地主机) - 它无法解析任何数据并给出

JSONException: Value of type java.lang.String cannot be converted to JSONObject

所以我认为问题出在我的服务器响应中。在浏览器中的响应看起来像

{
"items": [
    {
        "title": "Sometitle",
        "address": "Someaddress"
    },
    {
        "title": "Sometitle2",
        "address": "Someaddress2"
    }
]
}

和 json 验证器表明它是有效的。我研究了类似的问题,但没有找到解决方案,我不知道是什么原因。谁能提出解决方案?

更新。我的实际 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;
}

}

然后在我的 Activity:

          JsonParser jParser = new JsonParser();

          // get json string from url
          JSONObject json = jParser.getJSONFromUrl(ITEMS_URL);

          // get the array of items
          dataJsonArr = new JSONArray(json);

这可能是服务器端问题,在您点击服务器以获取响应的方法中,您必须首先在字符串变量中获得响应,尝试从那里获得响应,可能是您从那里获得了正确的响应..

实际问题是使用 HttpPost 请求,应该是 HttpGet。

来自API的响应可能是服务器端请求映射导致的错误响应。