android - 解析数据时出错 org.json.JSONException : Value ���� of type java. lang.String 无法转换为 JSONObject

标签 android mysql servlets

我正在尝试通过 servlet 使用 Json 对从 android studio 到 mySQL 的应用程序进行身份验证。 我不断收到此解析错误。以下是我的代码 fragment 。请帮助我。

android studio编写的MainActivity类

--------------
public class MainActivity extends ActionBarActivity {
    EditText uname, password;
    Button submit;

    JSONParser jParser = new JSONParser();

    JSONObject json;

    private static String url_login = "http://192.168.10.125:8080/CabbCallLogin/LoginServlet";
    //JSONArray incoming_msg = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewsById();
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View args0) {
                // execute method invokes doInBackground() where we open a Http URL connection using the given Servlet URL
                //and get output response from InputStream and return it.
                new Login().execute();

            }
        });
    }
    private void findViewsById() {

        uname = (EditText) findViewById(R.id.txtUser);
        password = (EditText) findViewById(R.id.txtPass);
        submit = (Button) findViewById(R.id.button1);
    }

    private class Login extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... args) {
            Log.e("Error001" , "I am in background");
            // Getting username and password from user input
            String username = uname.getText().toString();
            String pass = password.getText().toString();
            Log.e("Error004", "I have got the uname,pass");
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("u",username));

            params.add(new BasicNameValuePair("p",pass));
            Log.e("Error00", "I have got the name value pairs");

            json = jParser.makeHttpRequest(url_login, "GET", params);
            Log.e("Error00" , "I have sent the request");

            String s=null;

            try{
                s= json.getString("info");
                Log.e("Msg", json.getString("info"));
                Log.e("Error" , "I am in the try catch");
                if(s.equals("success")){
                    Log.e("Error1" , "I am in the if try catch");
                    Intent login = new Intent(getApplicationContext(), Welcome.class);
                    login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(login);
                    finish();

                }else{
                    Log.e("Error2" , "I am in the else try catch");
                       ErrorMessage("Error" , "I m in the else part of login");
                }

            }catch (JSONException e){
                Log.e("Error3" , "I am in the json try catch");
                e.printStackTrace();
                ErrorMessage("Error", "I m in the json exception part of login");
            }

                  return null;

        }
    }
    private void ErrorMessage(String Title , String Message){

        AlertDialog.Builder alertbuilder = new AlertDialog.Builder(MainActivity.this);

        alertbuilder.setMessage("Incorrect Credentials");
        alertbuilder.setPositiveButton("Ok", null);
        alertbuilder.show();

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

------------------------------------------

JSONParser class 
public class JSONParser {

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

    static InputStream iStream = null;
    static JSONArray jarray = null;

    public JSONParser() {

    }


    public JSONObject makeHttpRequest(String url_login, String method,
                                      List<NameValuePair> params) {

        // Making HTTP request

        Log.e("Error003" , "I am in the JSONOBJECT class");
        try {

            if(method == "POST"){
                // request method is POST
                // defaultHttpClient

                Log.e("Error003" , "I am in the JSONOBJECT post method");
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url_login);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                Log.e("Error003" , "I am in the JSONOBJECT get method");
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url_login += "?" + paramString;
                HttpGet httpGet = new HttpGet(url_login);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

                Log.e("Error004" , "I am at end the JSONOBJECT get method");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try{
            Log.e("Error003" , "I am in the Buffer class");
            BufferedReader reader = new BufferedReader(new InputStreamReader (is, "UTF-8"), 8);
            Log.e("Error004" , "I am in the Buffer class");
            StringBuilder sb = new StringBuilder();
            Log.e("Error005" , "I am in the Buffer class");
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();

        }catch (Exception e) {
            Log.e("Buffer Error1", "Error converting result " + e.toString());
        }
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser1", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }


    public JSONArray getJSONFromUrl(String url_login,String method,  List<NameValuePair> params) {



        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url_login);

        try{

            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e("==>", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            jarray = new JSONArray( builder.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser2", "Error parsing data " + e.toString());
        }
// return JSON Object
        return jarray;
    }

    public JSONObject makeHttpRequest2(String url_login) {


        // Making HTTP request
        try {

            // check for request method
            //if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url_login);
            //  httpPost.setEntity(new UrlEncodedFormEntity(params));

            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, "UTF-8"), 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 Error2", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser3", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
    }

最佳答案

当您的代码接收到的数据是字符串时,它需要一个 json 对象。 除非你希望你的android接收字符串,否则你应该检查服务/数据源

关于android - 解析数据时出错 org.json.JSONException : Value ���� of type java. lang.String 无法转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32820090/

相关文章:

php - 向服务器发送答案,并从服务器返回相关数组以供下一个输入选项

java - 如何使用注释使更具体的 urlPattern 覆盖更广泛的模式

java - com.google.gson.Gson 类因 javax.crypto.SecretKey 而失败?

带有正文参数的Android短信链接

mysql - 内连接查询中的数据排序

java - 如何从 web.xml 中排除特定路径?

java - 被拒绝的 bean 名称 'propertyConfigurer' : no URL paths identified

android - git push 如何与 android 的 repo 工具一起工作?

Android Studio,App 为 ActionBarActivity 抛出 java.lang.NoClassDefFoundError

c# - * 的类型初始值设定项引发异常