2015-10-19 90 views
-1

我想创建使用Android Java的JSON解析器。我是开发android JAVA的新人。我需要解析用户名和密码来获得一些操作,比如登录活动。低于我想使用的嵌套参数,如果url和验证成功,我会得到下面提到的响应。下面提到的URL解析参数。请帮帮我!解析JSON Android?

http://sample.com/login/username/ <username> /password <password>? 



    { 
     "response":{ 
        "School":"SBOA", 
        "Name":"Anitha", 
        "Class":"Tenth", 
        }, 
        "Result":"Good", 
    } 

下面的代码我想:

import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.loopj.android.http.AsyncHttpClient; 
import com.loopj.android.http.AsyncHttpResponseHandler; 
import com.loopj.android.http.RequestParams; 

/** 
* 
* Login Activity Class 
* 
*/ 
public class LoginActivity extends Activity { 
    // Progress Dialog Object 
    ProgressDialog prgDialog; 
    // Error Msg TextView Object 
    TextView errorMsg; 
    // Email Edit View Object 
    EditText emailET; 
    // Passwprd Edit View Object 
    EditText pwdET; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.login); 
     // Find Error Msg Text View control by ID 
     //errorMsg = (TextView)findViewById(R.id.login_error); 
     // Find Email Edit View control by ID 
     emailET = (EditText)findViewById(R.id.email); 
     // Find Password Edit View control by ID 
     pwdET = (EditText)findViewById(R.id.password); 
     // Instantiate Progress Dialog object 
     prgDialog = new ProgressDialog(this); 
     // Set Progress Dialog Text 
     prgDialog.setMessage("Please wait..."); 
     // Set Cancelable as False 
     prgDialog.setCancelable(false); 
    } 

    /** 
    * Method gets triggered when Login button is clicked 
    * 
    * @param view 
    */ 
    public void loginUser(View view){ 

     navigatetoHomeActivity(); 

     // Get Email Edit View Value 
     String email = emailET.getText().toString(); 
     // Get Password Edit View Value 
     String password = pwdET.getText().toString(); 
     // Instantiate Http Request Param Object 
     RequestParams usernames = new RequestParams(); 
     RequestParams passwords = new RequestParams(); 

     // When Email Edit View and Password Edit View have values other than Null 
     if(Utility.isNotNull(email) && Utility.isNotNull(password)){ 
      // When Email entered is Valid 
      if(Utility.validate(email)){ 
       // Put Http parameter username with value of Email Edit View control 
       usernames.put("username", email); 
       // Put Http parameter password with value of Password Edit Value control 
       passwords.put("password", password); 
       // Invoke RESTful Web Service with Http parameters 
       invokeWS(usernames); 
       invokeWS(passwords); 

      } 
      // When Email is invalid 
      else{ 
       Toast.makeText(getApplicationContext(), "Please enter valid email", Toast.LENGTH_LONG).show(); 
      } 
     } else{ 
      Toast.makeText(getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_LONG).show(); 
     } 

    } 

    /** 
    * Method that performs RESTful webservice invocations 
    * 
    * @param usernames 
    */ 
    public void invokeWS(final RequestParams usernames){ 
     // Show Progress Dialog 
     prgDialog.show(); 
     // Make RESTful webservice call using AsyncHttpClient object 
     AsyncHttpClient client = new AsyncHttpClient(); 
     client.get("URL" ,params,new AsyncHttpResponseHandler() { 


      // When the response returned by REST has Http response code '200' 
      @Override 
      public void onSuccess(String response) { 
       // Hide Progress Dialog 
       prgDialog.hide(); 
       try { 
        // JSON Object 
        JSONObject obj = new JSONObject(response); 
        // When the JSON response has status boolean value assigned with true 
        if(obj.getBoolean("response")){ 
         Toast.makeText(getApplicationContext(), "You are successfully logged in!", Toast.LENGTH_LONG).show(); 
         // Navigate to Home screen 
         navigatetoHomeActivity(); 
        } 
        // Else display error message 
        else{ 
         errorMsg.setText(obj.getString("error_msg")); 
         Toast.makeText(getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show(); 
        } 
       } catch (JSONException e) { 
        // TODO Auto-generated catch block 
        Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show(); 
        e.printStackTrace(); 

       } 
      } 
      // When the response returned by REST has Http response code other than '200' 
      @Override 
      public void onFailure(int statusCode, Throwable error, 
            String content) { 
       // Hide Progress Dialog 
       prgDialog.hide(); 
       // When Http response code is '404' 
       if(statusCode == 404){ 
        Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show(); 
       } 
       // When Http response code is '500' 
       else if(statusCode == 500){ 
        Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show(); 
       } 
       // When Http response code other than 404, 500 
       else{ 
        Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show(); 
       } 
      } 
     }); 
    } 

    /** 
    * Method which navigates from Login Activity to Home Activity 
    */ 
    public void navigatetoHomeActivity(){ 
     Intent homeIntent = new Intent(getApplicationContext(),WatchListActivity.class); 
     homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     startActivity(homeIntent); 
    } 
+1

您打算进行解析的Java代码在哪里?从哪里来的JSON数据? –

+0

对不起蒂姆。我尝试了很多代码,但它不工作。现在我没有任何正确的代码...给你的示例代码和正确的JSON过程。这对我会很有帮助! – android

+0

可能重复[java(android)从头开始创建JSONObject](http://stackoverflow.com/questions/7960858/java-android-create-jsonobject-from-scratch) –

回答

0

使用此代码从URL获取JSON。

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONParser { 

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

    // constructor 
    public JSONParser() { 

    } 

    public JSONObject getJSONFromUrl(String url) { 

     // Making HTTP request 
     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      //name value pairs for posting username and password 
    List<NameValuePair> params = new ArrayList<NameValuePair>(); 
    params.add(new BasicNameValuePair("username","john")); 
    params.add(new BasicNameValuePair("password","123")); 
    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, "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 parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

    } 
} 

在您的活动中调用此json解析器与您的url在AsyncTask中。

获取JSON数据JSON学习一些基础知识从w3schools 查看完整的代码here

+0

首先我想说100谢谢! @ Akhil.I将尝试标记它是正确的答案。请给我几分钟! – android

+0

我想在上面提到的url中发送用户名和密码。我正在进行登录活动。可以请在该嵌套网址中提及“如何传递”用户名和密码? – android

+1

http://stackoverflow.com/questions/16079991/send-a-string-on-android-with-httppost-without-using-namevaluepairs –

0

后,我建议你制作JSON字符串读Gson tutorial和使用Volley libary,使请求和响应。

+0

艾哈迈德,即使我不知道JSON。为此我问。请帮助我,我上面提到了我的代码。在那里如何解析两个参数到另一个方法。 – android

+1

@android,你应该问问题之前足够的搜索。 PLZ阅读[这个JSON教程](http://www.tutorialspoint.com/android/android_json_parser.htm) –