如何将String转换为JSONObject?

时间:2015-10-26 05:07:42

标签: android json android-volley

我有一个障碍,通过将数据字符串更改为jsonobject,是他的org.json.JSONException脚本错误:值

我正在尝试编码

btnLogin.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            String username = inputUser.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();

            // Check for empty data in the form
            if (username.trim().length() > 0 && password.trim().length() > 0) {
                Map<String,String> params = new HashMap<>();
                params.put("username", inputUser.getText().toString());
                params.put("password", inputPassword.getText().toString());
                sendPostRequest(params);
            } else {
                // Prompt user to enter credentials
                Toast.makeText(getApplicationContext(),
                        "Silahkan Masukan Username dan Password!", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

public void sendPostRequest(Map<String, String> params) {
    showDialog();
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "http://www.chris-chris.webege.com/login.php";

    mCustomRequest = new CustomRequest(Request.Method.POST,
            url, params, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Intent intent = new Intent(Login.this,
                    Coba.class);
            startActivity(intent);
            finish();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Error", error.getMessage());
            hidepDialog();
            Toast.makeText(Login.this, "Belum Terhubung Internet! ", Toast.LENGTH_SHORT).show();
        }
    });
    mCustomRequest.setRetryPolicy(new DefaultRetryPolicy(Template.VolleyRetryPolicy.SOCKET_TIMEOUT,
            Template.VolleyRetryPolicy.RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(mCustomRequest);
}

2 个答案:

答案 0 :(得分:3)

将字符串转换为JSONObject有两个条件:

1。该字符串应采用适当的Json格式。

2。将代码放在try catch块中。

示例:

String jsonString  = "{"status":"1","message":"Login successfully","data":{"uid":"1","email":"baleshwar@gmail.com","password":"202cb962ac59075b964b07152d234b70","name":"","role":"1","gender":"","address":"","image":"","is_active":"0","last_login":"0000-00-00 00:00:00","device_id":"0","created_at":"2015-06-03 06:01:02","updated_at":"2015-06-03 11:01:02","location":"","dob":"0000-00-00","descriptions":""}}"

现在将此字符串转换为JSONObject

    try{
        JSONObject jsonResponse = new JSONObject(result);
    }catch(Exception e){
    e.printStackTrace();

}

答案 1 :(得分:0)

试试这个,

如果您致电您的服务并尝试将该代码粘贴到isSucsess部分

JSONObject jObject = jsonObject.getJSONObject("jsonobjectname");    
tvTitle.setText(jObject.getString("your string name"));
相关问题