JSONException:无法将 java.lang 类型的值 <!DOCTYPE 转换为 JSONObject

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19872822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:56:56  来源:igfitidea点击:

JSONException: Value <!DOCTYPE of type java.lang cannot be converted to JSONObject

javaandroidjson

提问by Daniel Sibaja

Guys can you help me a little bit, Im getting this error:

伙计们,你能帮我一下吗,我收到这个错误:

"JSONException: Value <!DOCTYPE of type java.lang cannot be converted to JSONObject"

When I'm parsing the data here is my code:

当我解析数据时,这里是我的代码:

    public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONParser() {

    }
    public JSONObject getJSONFromUrl(String url) {

        // Making 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 + "\n");
            }
            is.close();
            json = sb.toString();

        }catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

}

Here is the code where I'm instantiating the Parser:

这是我实例化解析器的代码:

private void fillSpinnerCabTypes() {        
    List<String> cabTypesSpinner = new ArrayList<String>();
    JSONParser jsonParser = new JSONParser();
    JSONObject cabTypesObject = jsonParser.getJSONFromUrl(urlTypeCabs);
    try{
        TypesArray = cabTypesObject.getJSONArray(TAG_TYPES);

        for(int i = 0; i < TypesArray.length(); i++){
            JSONObject c = TypesArray.getJSONObject(i);
            String name = c.getString(TAG_NAME);
            cabTypesSpinner.add(name);
        }
    }catch(Exception e ){
        e.printStackTrace();
    }       

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                  android.R.layout.simple_spinner_item, cabTypesSpinner);

     final Spinner spnCabTypes = (Spinner)findViewById(R.id.spnTypeOfCab);
     adapter.setDropDownViewResource(
                            android.R.layout.simple_spinner_dropdown_item);
     spnCabTypes.setAdapter(adapter);
}

I'm really stuck with this. I'm populating the spinner from a database in a backend on Django in the server.

我真的被这个困住了。我正在从服务器中 Django 后端的数据库中填充微调器。

This is my JSON data

这是我的 JSON 数据

{"Types": [{"name": "Normal"}, {"name": "Discapacitados"}, {"name": "Buseta"}]}

回答by Simon Marquis

This issue comes from the server.
The URL you're requesting, send you back data but not in the JSON format.
The Exception you get is telling you that the String the server send you back starts with:

这个问题来自服务器。
您请求的 URL 向您发送回数据,但不是 JSON 格式。
您得到的异常告诉您服务器发送给您的字符串以以下内容开头:

<!DOCTYPE 

This can be:

这可以是:

  1. A simple webpage (instead of raw JSON). It correspond to the first XML tag of a web page (source)
  2. An error page generated by the server, and printed in HTML
  1. 一个简单的网页(而不是原始 JSON)。它对应于网页的第一个 XML 标签(来源
  2. 服务器生成的错误页面,并以 HTML 格式打印

To debug this further, simply print the content of your jsonvariable in the logcat:

要进一步调试,只需json在 logcat 中打印变量的内容:

Log.d("Debug", json.toString());
jObj = new JSONObject(json);

回答by Passion

This problem came in my code also.and solution was different.It occured due to spelling mistake of webservice.

这个问题也出现在我的代码中。解决方案是不同的。它是由于webservice的拼写错误而发生的。

Solution 1:

解决方案1:

for example real the url is

例如真实的网址是

http://example.com/directory/file.php

http://example.com/directory/file.php

and i had used

我用过

http://example.com/directory/file1.php

http://example.com/directory/file1.php

Solution 2: use loopj library .it exactly gives you the explained error.

解决方案 2:使用 loopj 库。它正好给你解释的错误。

AsyncHttpClient client = new AsyncHttpClient();
        client.post(str , localRequestParams, new AsyncHttpResponseHandler() {

            @Override
            public void onFinish() {
                super.onFinish();
                Log.i("onFinish","onFinish");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                Log.i("onSuccess","onSuccess");



            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.i("onFailure","onFailure");


            }

        });