2017-01-06 130 views
1

這是我的JSON解析器類JSON解析錯誤(追加結果)

public class JSONParser { 

    String charset = "UTF-8"; 
    HttpURLConnection conn; 
    DataOutputStream wr; 
    StringBuilder result = new StringBuilder(); 
    URL urlObj; 
    JSONObject jObj = null; 
    StringBuilder sbParams; 
    String paramsString; 

    public JSONObject makeHttpRequest(String url, String method, 
             HashMap<String, String> params) { 

     sbParams = new StringBuilder(); 
     int i = 0; 
     for (String key : params.keySet()) { 
      try { 
       if (i != 0){ 
        sbParams.append("&"); 
       } 
       sbParams.append(key).append("=") 
         .append(URLEncoder.encode(params.get(key), charset)); 

      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } 
      i++; 
     } 

     if (method.equals("POST")) { 
      // request method is POST 
      try { 
       urlObj = new URL(url); 

       conn = (HttpURLConnection) urlObj.openConnection(); 

       conn.setDoOutput(true); 

       conn.setRequestMethod("POST"); 

       conn.setRequestProperty("Accept-Charset", charset); 

       conn.setReadTimeout(10000); 
       conn.setConnectTimeout(15000); 

       conn.connect(); 

       paramsString = sbParams.toString(); 

       wr = new DataOutputStream(conn.getOutputStream()); 
       wr.writeBytes(paramsString); 
       wr.flush(); 
       wr.close(); 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     else if(method.equals("GET")){ 
      // request method is GET 

      if (sbParams.length() != 0) { 
       url += "?" + sbParams.toString(); 
      } 

      try { 
       urlObj = new URL(url); 

       conn = (HttpURLConnection) urlObj.openConnection(); 

       conn.setDoOutput(false); 

       conn.setRequestMethod("GET"); 

       conn.setRequestProperty("Accept-Charset", charset); 

       conn.setConnectTimeout(15000); 

       conn.connect(); 

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

     } 

     try { 
      //Receive the response from the server 
      InputStream in = new BufferedInputStream(conn.getInputStream()); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 

      String line; 
      while ((line = reader.readLine()) != null) { 
       result.append(line); 
      } 

      Log.d("JSON Parser", "result: " + result.toString()); 

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

     conn.disconnect(); 

     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(result.toString()); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON Object 
     return jObj; 
    }} 

的AsyncTask

class CreateNewProduct extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      mView=new CatLoadingView(); 
      mView.show(getSupportFragmentManager(),""); 
     } 
     protected String doInBackground(String... args) { 
      int success; 
      String name = inputName.getText().toString(); 
      String password = inputPassword.getText().toString(); 
      try { 
       // Building Parameters 
       HashMap<String,String> h1=new HashMap<>(); 
       h1.put("username", name); 
       h1.put("password", password); 
       // getting JSON Object 
       //url accepts POST method 
       JSONObject json= jsonParser.makeHttpRequest(api_url,"POST", h1); 
       // check log cat from response 
       Log.e("Create Response 1", json.toString()); 
       JsonData=json.toString(); 
       JSONObject reader=new JSONObject(JsonData); 
       JSONObject jobj=reader.getJSONObject("user"); 
       Log.e("Create Response 2", jobj.toString()); 
        JSONObject jobj2 = jobj.getJSONObject("data"); 
        String user_id = jobj2.getString("USER_NAME"); 
        //String bimage=jobj2.getString("DISPLAY_PIC"); 
        Intent intent = new Intent(getBaseContext(), MainActivity.class); 
        intent.putExtra("id", user_id); 
        // intent.putExtra("image",bimage); 
        startActivity(intent); 
      } catch (JSONException e) { 
       e.printStackTrace(); 

      } 
      // check for success tag 
      return null; 
     } 
     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once done 
      mView.dismiss(); 


     } 

1:當我輸入正確的登錄憑據登錄會成功,而

JSONResult is

{"user":{"data":{"USER_ID":"1","USER_NAME":"Vaisakh CV","BRANCH_ID":"1"}}} . 

2:但是,當我輸入錯誤的憑據的JSONResult是

{"user":{"error":"Invalid data!"}} 

3:我的問題是後輸入正確的憑據錯誤嘗試JSONResult是

{"user":{"error":"Invalid data!"}}{"user":{"data":{"USER_ID":"1","USER_NAME":"Vaisakh CV","BRANCH_ID":"1"}}} 

我需要後只有

{"user":{"data":{"USER_ID":"1","USER_NAME":"Vaisakh CV","BRANCH_ID":"1"}}} 

如何爲r解決這個問題?提前致謝!

回答

0

對於解析數據,您必須先檢查密鑰是否存在。使用has方法檢查鍵「數據」和「錯誤」是否存在。如果響應具有關鍵「錯誤」,則應顯示錯誤消息。如果響應具有關鍵的「數據」,則可以解析它並顯示數據。

JSONObject reader = new JSONObject(JsonData); 
JSONObject jobj = reader.getJSONObject("user"); 
if(jobj.has("data")) { 
    // parse data 
} else if(jobj.has("error")) { 
    // raise error 
} 

爲了您的JSON的第二個問題得到加起來,

你有創造了一個StringBuilder全球。所以當你再次請求時,它將被連接。爲了防止出現這種情況,請清除StringBuilder或按照以下方式重新初始化它。

result = new StringBuilder(); // add this line 
String line; 
while ((line = reader.readLine()) != null) { 
    result.append(line); 
} 
+0

哇!你給我我想要的!謝謝...! :)字符串追加是我的主要問題..!你讓我今天一整天都感覺很好!再一次感謝你! –

0

可以使用

jsonobject.optString("key"); 

oppString只有當具有相同的密鑰的JSONObject進行。它不會崩潰。

0

如果你定製這個,你可以得到解決方案,但實際的問題來自服務器端。服務器沒有以適當的方式返回數據。當你輸入正確的憑證時,我正在給出什麼迴應。

{"status":"true","user":{"data":{"USER_ID":"1","USER_NAME":"Vaisakh CV","BRANCH_ID":"1"}}} . 

當您輸入錯誤的憑證時,回覆必須是。

{"status":"false"}. 

這將是更好的選擇,爲您解析服務

或者你可以解析這個樣子。如果你輸入一個catch block,這意味着你輸入了錯誤的憑據,否則你輸入正確

try { 
      JSONObject jsonObject = new JSONObject("response"); 
      JSONObject user = jsonObject.getJSONObject("user"); 
      JSONObject data = user.getJSONObject("data"); 
      String userId = data.getString("USER_ID"); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      Toast.makeText(this, "Wrong Credentials", Toast.LENGTH_LONG).show(); 
     }