2013-05-03 111 views
1

所以即時通訊試圖找出解析下面的JSON URL的最有效方法,我將在Android上使用Java進行此操作。解析JSONObjects和JSONArray的最佳方式

JSONParser.java

public class JSONParser { 

private static final Context context = null; 
static InputStream is = null; 
static JSONObject jarray = null; 
static JSONArray jarray2 = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 
public JSONObject getJSONFromUrl2(String url) { 

     StringBuilder builder = new StringBuilder(); 
     HttpClient client = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(url); 
     try { 
      HttpResponse response = client.execute(httpGet); 
      StatusLine statusLine = response.getStatusLine(); 
      int statusCode = statusLine.getStatusCode(); 
      if (statusCode == 200) { 
      HttpEntity entity = response.getEntity(); 
      InputStream content = entity.getContent(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(content)); 
      String line; 
      while ((line = reader.readLine()) != null) { 
       builder.append(line); 
      } 
       //Recommended by Ted Hopp 
       return new JSONObject(builder.toString()); 
      } else { 
      Log.e("==>", "No Response, Check Your API KEY"); 
      Toast.makeText(context,"Error Response, Check your API Key", Toast.LENGTH_LONG).show(); 
      } 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     } catch (JSONException e) { 
     Log.e("JSON Parser Activity", url + e.toString()); 
    } 
    // return JSON String 
    return null; 
} 

現在主要ISSUE IM已經在使用我的JSONParser活動的一部分,2解析的JSONObject。

https://api.company.com/api/systems/165756/summary?&key=e1e63de7276b04c9bb99adfd45b3a14c

返回以下JSON

{ 
    "energy_month": 31132, 
    "current_power": 1963, 
    "modules": 24, 
    "energy_today": 1577, 
    "system_id": 165756, 
    "energy_week": 215504, 
    "source": "microinverters", 
    "energy_lifetime": 1545467, 
    "summary_date": "2013-05-03T00:00:00-07:00" 
} 

    protected ArrayList<String> doInBackground(final String... args) { 

      JSONParser jParser = new JSONParser(); 
      arrfortextviews=new ArrayList<String>(); 
      JSONObject json2 = jParser.getJSONFromUrl2(https://api.company.com/api/systems/165756/summary?&key=e1e63de7276b04c9bb99adfd45b3a14c); 
        //Added due to for some reason index return has more than 1 
     for (int i = 0; i < json2.length(); i++) { 
         try {      
        Log.e("JSON Parser", summary + args.toString()); 
        String current_power = json2.getString(TAG_CURRENT_POWER); 
        String energy_lifetime = json2.getString(TAG_ENERGY_LIFETIME); 

但是這個當前的代碼我碰到下面的錯誤。

05-03 11:31:59.765: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0 
05-03 11:31:59.765: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0 
05-03 11:31:59.780: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0 
05-03 11:31:59.780: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0 
05-03 11:31:59.785: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0 
05-03 11:31:59.785: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0 
05-03 11:31:59.790: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0 
05-03 11:31:59.790: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0 
05-03 11:31:59.790: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0 
05-03 11:31:59.895: E/SpannableStringBuilder(30625): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 
05-03 11:31:59.895: E/SpannableStringBuilder(30625): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 
+0

我會建議不要在該請求被做了相同的異步任務解析JSON。 AsyncTask的響應和你的活動之間的一個層可以有更精細的錯誤處理,跨請求代碼重用,以及記錄連接問題,服務器錯誤,JSON解析錯誤等。 – 2013-05-03 15:20:49

+0

@iambmelton我更新了我的代碼 - 你介意採取第二次看 – 2013-05-03 15:40:31

回答

1

看看JSONObject這個課。它是標準Android發行版的一部分。

JSONObject thing = new JSONObject(jsonString); 

然後你只需要導航的thing對象結構來得到你需要的數據:由於代碼可以很簡單。

getJSONFromUrl2方法看起來是這樣的:

public JSONObject getJSONFromUrl2(String url) { 
    StringBuilder builder = new StringBuilder(); 
    HttpClient client = new DefaultHttpClient(); 
    HttpGet httpGet = new HttpGet(url); 
    try { 
     HttpResponse response = client.execute(httpGet); 
     StatusLine statusLine = response.getStatusLine(); 
     int statusCode = statusLine.getStatusCode(); 
     if (statusCode == 200) { 
      HttpEntity entity = response.getEntity(); 
      InputStream content = entity.getContent(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(content)); 
      String line; 
      while ((line = reader.readLine()) != null) { 
       builder.append(line); 
      } 
      return new JSONObject(builder.toString()); 
     } else { 
      Log.e("==>", "No Response, Check Your API KEY"); 
      Toast.makeText(context,"Error Response, Check your API Key", Toast.LENGTH_LONG).show(); 
     } 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     Log.e("JSON Parser", json + url + e.toString()); 
    } 
    return null; // only gets here on an error 
} 

它遺漏了一點錯誤處理,但因爲你原來的代碼也失蹤了,我假設的工作,你最終會做反正。

+0

感謝您的答案,我有一個JSONParser活動即時通訊使用,我上面張貼。現在的問題是我不能解析JSONObject與我的JSONParser活動的第二部分使用'getJSONFromUrl2'而不是'getJSONFromUrl'解析JSONObject – 2013-05-03 15:35:17

+0

@JaisonBrooksDevelopment - 你似乎已經註釋瞭解析的代碼。爲什麼你不能解析對象?你有沒有試過簡單的'返回新的JSONObject(builder.toString());'在'try'塊中? – 2013-05-03 16:20:45

+0

你的意思是這樣的' \t \t嘗試{\t \t \t \t // JSONObject的jobj2 =新的JSONObject(builder.toString()); \t \t \t return new JSONObject(builder.toString()); \t \t \t // jarray = jobj2。getJSONObject( 「摘要」); \t \t}趕上(JSONException E){ \t \t} \t \t //返回JSON字符串 \t \t返回jobj2; ' – 2013-05-03 16:58:21

1

您可以使用google提供的Volley庫。
它有許多好處,如緩存,內存管理和排隊請求。
您可以在這裏找到一個最好的解決方案:
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

+0

感謝這個資源。我通過使用GSON發現了一個解決方案。但是Volley聽起來很好用。你有很多經驗嗎? – 2014-10-17 18:51:26