2016-01-22 36 views
0

我想用json創建一個登錄和註冊系統。 我想先獲取url的內容,然後解析json字符串。 Json String sample:在android中解析簡單的json字符串

{ "employee":{"mesg":"username is exsist!","id":0,"name":0,"username":0,"email":0,"status":500} } 

我只需要mesg或狀態。 我無法解析它。我想解析這個字符串,每次,我的應用程序給力停止

這是我的代碼:

package com.sourcey.materiallogindemo; 

import android.app.ProgressDialog; 

import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.View; 

import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 



import butterknife.Bind; 
import butterknife.ButterKnife; 

public class SignupActivity extends AppCompatActivity { 

    //URL to get JSON Array 

    //JSON Node Names 



    public String nurl; 


    private static final String TAG = "SignupActivity"; 

    @Bind(R.id.input_name) EditText _nameText; 
    @Bind(R.id.input_email) EditText _emailText; 
    @Bind(R.id.input_tell) EditText _tellText; 
    @Bind(R.id.input_password) EditText _passwordText; 
    @Bind(R.id.btn_signup) Button _signupButton; 
    @Bind(R.id.link_login) TextView _loginLink; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_signup); 
     ButterKnife.bind(this); 

     _signupButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       signup(); 
      } 
     }); 

     _loginLink.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // Finish the registration screen and return to the Login activity 
       finish(); 
      } 
     }); 
    } 



    public void signup() { 
     Log.d(TAG, "Signup"); 

     if (!validate()) { 
      onSignupFailed(); 
      return; 
     } 

     _signupButton.setEnabled(false); 

     final ProgressDialog progressDialog = new ProgressDialog(SignupActivity.this, 
       R.style.AppTheme_Dark_Dialog); 
     progressDialog.setIndeterminate(true); 
     progressDialog.setMessage("در حال انجام عملیات..."); 
     progressDialog.show(); 

     String name = _nameText.getText().toString(); 
     String email = _emailText.getText().toString(); 
     String tell = _tellText.getText().toString(); 
     String password = _passwordText.getText().toString(); 

     // TODO: Implement your own signup logic here. 

     nurl = "http://someurl/json/user.php?type=register&mobile="+tell+"&p="+password+"&email="+email+"&name="+name; 

     //new JSONParse().execute(); 

     new android.os.Handler().postDelayed(
       new Runnable() { 
        public void run() { 

         onSignupSuccess(); 
         progressDialog.dismiss(); 


        } 
       }, 3000); 
    } 


    public void onSignupSuccess() { 
     _signupButton.setEnabled(true); 
     setResult(RESULT_OK, null); 
     finish(); 
    } 

    public void onSignupFailed() { 
     Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show(); 

     _signupButton.setEnabled(true); 
    } 

    public boolean validate() { 
     boolean valid = true; 

     String name = _nameText.getText().toString(); 
     String email = _emailText.getText().toString(); 
     String tell = _tellText.getText().toString(); 
     String password = _passwordText.getText().toString(); 

     if (name.isEmpty() || name.length() < 3) { 
      _nameText.setError("at least 3 characters"); 
      valid = false; 
     } else { 
      _nameText.setError(null); 
     } 

     if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) { 
      _emailText.setError("enter a valid email address"); 
      valid = false; 
     } else { 
      _emailText.setError(null); 
     } 

     if (tell.isEmpty() || !android.util.Patterns.PHONE.matcher(tell).matches()) { 
      _tellText.setError("enter a valid phone number"); 
      valid = false; 
     } else { 
      _tellText.setError(null); 
     } 

     if (password.isEmpty() || password.length() < 4 || password.length() > 10) { 
      _passwordText.setError("between 4 and 10 alphanumeric characters"); 
      valid = false; 
     } else { 
      _passwordText.setError(null); 
     } 



     return valid; 
    } 













} 

現在我不知道我能做些什麼確切地解析字符串,得到的只是狀態或MESG,謝謝掌舵。我非常需要這個,對於一個成熟的問題感到抱歉。 關於

+0

其中U試圖解析發佈JSON字符串 –

+0

你有一些很好的答案顯示代碼示例代碼。我建議你使用這裏的答案之一,而不是創建一個新的問題。 – Knossos

回答

1

您可以使用JSONObject執行此任務。

例如(省略的try/catch):

JSONObject root = new JSONObject(jsonString); 
JSONObject employee = root.getJSONObject("employee"); 
String message = employee.getString("name"); 
String username = employee.getString("username"); 
String email = employee.getString("email"); 
int id = employee.getInt("id"); 
int status = employee.getInt("status"); 

如果你不知道你的JSON的一致性,你應該先check whether the key exists

您還應該檢查您的JSON數據類型,您似乎有名稱,用戶名和電子郵件的整數。但是,那些很少是整數。

JSONObject Documentation

1

使用排庫正從如下網址JSON響應 -

首先在你的項目模塊添加庫:應用程序依賴如下 -

dependencies { 
compile 'com.mcxiaoke.volley:library-aar:1.0.1' 
... 
} 

下面的代碼使用擺脫排球圖書館響應 -

// Instantiate the RequestQueue. 
    RequestQueue queue = Volley.newRequestQueue(this); 
    String url = "WEBSERVICE_URL"; // eg:- "http://www.google.com"; 

    // Request a string response from the provided URL. 
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { 

       @Override 
       public void onResponse(String response) { 
        System.out.println("Response is: " + response); 
        try { 
         JSONObject jobj = new JSONObject(response); 
         JSONObject jEmp = jobj.getJSONObject("employee"); 
         String message = jEmp.getString("mesg"); 
         int Status = jEmp.getInt("status"); 

        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 

       } 
      }, new Response.ErrorListener() { 

       @Override 
       public void onErrorResponse(VolleyError error) { 

        if(error.networkResponse != null && error.networkResponse.data != null){ 
         VolleyError verror = new VolleyError(new String(error.networkResponse.data)); 
         System.out.println("That didn't work!\n" + error.toString()); 
        } 

       } 

    }); 

    // Add the request to the RequestQueue. 
    queue.add(stringRequest); 

您可以分析如下的JSON -

try { 
     JSONObject jobj = new JSONObject(responseJSONString); 
     JSONObject jEmp = jobj.getJSONObject("employee"); 
     String message = jEmp.getString("mesg"); 
     int Status = jEmp.getInt("status"); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

`responseJSONString` is the JSON response you got. 
+0

它工作的很好,謝謝你...第二個問題,我有這個,我怎麼可以從網址的內容,並把變量..我工作的PHP,在PHP中我們有file_put_contents和相同的內容與變量,在Android我知道我該怎麼做,謝謝 – persian

+0

@persian:most wc :)接受n upvote – kevz

+0

@persian:查看我的編輯 – kevz

1

有些庫可以幫助你解析Json,你可以使用gsonJackson。我實際上使用了retrofit 來調用我的API,因爲它允許你插入一個json解串器,然後它只是爲你做所有的工作。它還處理所有的HTTP調用,使用起來相當簡單。

1

建議您與Volley一起去。下面是同一

JsonObjectRequest jsonObjReqfirst = new JsonObjectRequest(Request.Method.GET,urlBuffer.toString(),null, 
        new Response.Listener<JSONObject>(){ 

         @Override 
         public void onResponse(JSONObject response) { 
          Log.i(Constants.NETLOG, "Volley response= " + response.toString()); 
          getResponseprocessed(response)); 

         } 
        }, new Response.ErrorListener(){ 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        Log.e(Constants.NETLOG, "VolleyError response= " + error.toString()); 

       } 
      }); 
      Volley.newRequestQueue(mContext).add(jsonObjReqfirst); 

void getResponseprocessed(JSONObject response){ 
      try { 
       JSONObject statusObj = response.getJSONObject("employee"); 
       String mseg=statusObj.getString("mesg"); 
       int status = statusObj.getInt("status"); 

      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
    }