2015-11-06 91 views
0

我以JSON以下數據我怎麼會從這個文件中檢索數據從android中通過php檢索Json的數據?

{"first_name":"immi","last_name":"Ahmad","contact_no":"0333333","dob":"2010-09-29","gender":"Male","pro_id":"3"} 

也即時通訊使用HTTP請求從android.i希望得到各個領域,並將其存儲在一個局部變量來存取權限這個文件android.i嘗試了以下,但徒勞無功。

JSONObject json_data = new JSONObject(result); 
      json_data.getJSONObject("userinfo"); 
      json_data.getString("first_name"); 

這是我的Android完整的類

public class ProfileActivity extends ActionBarActivity { 

    //data for through http request 
    static InputStream is = null; 
    String result = "flag"; 
    String line = null; 
    int userId; 
    String action="select"; 
    String workTable="user"; 

    ArrayList<HashMap<String, String>> personList; 

    //till here for through http request 

    @Override 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_profile); 


     userId = ((GlobalValues) this.getApplication()).getUserId(); 

     Toast.makeText(ProfileActivity.this, "user id is"+userId, Toast.LENGTH_SHORT).show(); 

     select(); 




     //for retrieval oncreate 

    } 
    public void select() { 


     final ArrayList<HashMap<String, String>> personList; 
     personList = new ArrayList<HashMap<String, String>>(); 

     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

     nameValuePairs.add(new BasicNameValuePair("action", action)); 
     nameValuePairs.add(new BasicNameValuePair("worktable",workTable)); 
     nameValuePairs.add(new BasicNameValuePair("user_id",String.valueOf(userId))); 



     try { 
      HttpClient httpclient = new DefaultHttpClient(); 

      HttpPost httppost = new HttpPost("http......"); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 
      Log.e("pass 1", "connection success "); 
     } catch (Exception e) { 
      Log.e("Fail 1", e.toString()); 
      Toast.makeText(getApplicationContext(), "Invalid IP Address", 
        Toast.LENGTH_LONG).show(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader 
        (new InputStreamReader(is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      result = sb.toString(); 
      Log.e("pass 2", "connection success "); 
     } catch (Exception e) { 
      Log.e("Fail 2", e.toString()); 
     } 

     try { 
       JSONObject userinfo= new JSONObject(result); 

     String fname= userinfo.getString("first_name"); 
     Toast.makeText(ProfileActivity.this, "name is"+fname, Toast.LENGTH_SHORT).show(); 

      String fname= userinfo.getString("first_name"); 
      Toast.makeText(ProfileActivity.this, "name is"+fname, Toast.LENGTH_SHORT).show(); 
      // JSONArray peoples = json_data.getJSONArray("userinfo"); 


      /* for (int i = 0; i < peoples.length(); i++) { 

       JSONObject c = peoples.getJSONObject(i); 
       String first_name = null, last_name = null, gender = null,contact_number=null,dob=null,profession_id=null; 
       first_name = c.getString("first_name"); 
       last_name = c.getString("last_name"); 
       contact_number = c.getString("contact_no"); 
       dob=c.getString("dob"); 
       gender=c.getString("gender"); 
       profession_id=c.getString("pro_id"); 

       final HashMap<String, String> persons = new HashMap<String, String>(); 
       persons.put("firstName", first_name); 
       persons.put("last_name", last_name); 
       persons.put("contact_number", contact_number); 
       persons.put("gender", gender); 
       persons.put("dob", dob); 
       persons.put("pro_id", profession_id); 
       personList.add(persons); 
       Toast.makeText(ProfileActivity.this, "your name is "+first_name, Toast.LENGTH_SHORT).show(); 

      }*/ 
     }catch (Exception e){ 
      Log.e("fil 3",e.toString()); 
     } 
    } 


    @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_profile, 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 
     item.getItemId(); 
     switch (item.getItemId()) { 
      case R.id.action_settings: 
       goToHome(); 
       return true; 



      default: 
       return super.onOptionsItemSelected(item); 
     } 


    } 

    public void goToHome(){ 

     Intent gotohome =new Intent(this,MapsActivity.class); 
     startActivity(gotohome); 
    } 

    public void goToEditProfile(View view){ 


     Intent gotoeditprofile=new Intent(this,TabedActivity.class); 


     startActivity(gotoeditprofile); 

    } 

} 

,這是我的PHP statment返回JSON作爲上述

$user_id= $_GET['user_id']; 
     $sqlselectuser="SELECT first_name,last_name,contact_no,dob,gender,pro_id FROM user WHERE user_id='$user_id'";   
    $ansuser=mysqli_query($con,$sqlselectuser); 
        $resuser=mysqli_fetch_assoc($ansuser); 
      if($resuser['dob']=="0000-00-00"){ 
       $userinfo = array("first_name"=>$resuser['first_name'],"last_name"=>$resuser['last_name'], 
       "contact_no"=>$resuser['contact_no'],"dob"=>date("Y-m-d"),"gender"=>$resuser['gender'], 
       "pro_id"=>$resuser['pro_id']); 
       echo json_encode($userinfo); 

回答

1

如果你的性反應是不是@tiny陽光大方法行不通

你不能做到像

 JSONObject userinfo= new JSONObject(result); 
    userinfo.getString("first_name"); 
    JSONObject someObject = userinfo.getJsonObject("somthing") 
    JSONObject somthingElse = someObject.getJsonObject("somthingElse") 

這變得過於忙碌,幾乎浪費你的時間

那麼最好的答案是Gson Liabrary

Gson gson = new GsonBuilder().create(); 
Movie movie = gson.fromJson(response, Movie.class); 

聽到電影是您從JSON映射類 - 顯示在下面的鏈接

,你可以做老虎鉗varsa也

Gson gson = new GsonBuilder().create(); 
Responce mResponce = gson.fromJson(jsonStr , Responce .class); 
String mName =mResponce.result.name; 

https://stackoverflow.com/a/41218155/4741746

希望您能理解其中的答案是最好的

+0

非常感謝...晚上代表,但幫助了我 –

1
JSONObject userinfo= new JSONObject(result); 

      userinfo.getString("first_name"); 

嘗試使用Gson簡化它!

+0

#小小的陽光,它顯示我這個異常值類型java.lang.String無法轉換爲JSONObject它的意思是什麼? –

+0

{「first_name」:「immi」,「last_name」:「Ahmad」,「contact_no」:「0333333」,「dob」:「2010-09-29」,「gender」:「男」,「pro_id」: 「3」}是你的結果? –

+0

Plz上傳異常截圖。 –

0

這就是你的json文件的所有內容?

您應該創建一個類來存儲每個json對象的信息。

例如創建PersonalInformation類有有情況「名字」,「姓氏」,「性別」 ......

然後我們使用一個for循環語句來閱讀所有信息。

希望得到這個幫助!