2015-04-02 36 views
0

我一直在研究如何從服務器查詢JSON數據並解析它以便在我的應用程序中使用。但是,我發現了許多不同的方法來做同樣的事情。我意識到有不同的JSON解析器,所以我們假設我堅持使用標準解析器。我的主要問題與服務器請求有關。這是我目前我MapActivityAndroid:處理JSON數據的最佳做法

private class DownloadJSON extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // Create a Progress Dialog 
     mProgressDialog = new ProgressDialog(MapActivity.this); 
     mProgressDialog.setTitle("Downloading Data"); 
     mProgressDialog.setMessage("Loading..."); 
     mProgressDialog.setIndeterminate(false); 
     mProgressDialog.show(); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     // Create an array 
     arraylist = new ArrayList<HashMap<String, String>>(); 

     try { 
      // Retrieve JSON Objects from the given URL address 
      jsonarray = JSONFunctions.getJSONfromURL("myurl"); 

      for (int i = 0; i < jsonarray.length(); i++) { 
       HashMap<String, String> map = new HashMap<String, String>(); 
       JSONObject obj = jsonarray.getJSONObject(i); 

       // Retrieve JSON Objects 
       map.put("id", String.valueOf(i)); 
       map.put("name", obj.getString("name")); 

       // Set the JSON Objects into the array 
       arraylist.add(map); 
      } 

     } catch (JSONException e) { 
      Log.e("Error", e.getMessage()); 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void args) { 
     // Do something with data 
     mProgressDialog.dismiss(); 
    } 
} 

代碼如果我JSON數據的結構看起來怪異,那是因爲它是存儲在一個未命名的數組,所以我不必須先創建一個對象。無論如何......我基本上是基於this tutorial。但是,他們有更多的代碼。這一切是否真的有必要?我不這麼認爲。我搜索了更多,發現其他使用了一半代碼的例子,基本上做了同樣的事情。因此,作爲一名開始的Android程序員,我的問題是處理JSON數據的最佳做法是什麼?謝謝! JSON文件的

例子:

[ 
    { 
     "name": "test", 
     "lat": "42.01108", 
     "long": "93.679196" 
    }, 
    { 
     "name": "test", 
     "lat": "42.01108", 
     "long": "93.679196" 
    } 
] 
+0

請出示從服務器返回 – 2015-04-02 03:57:45

+0

JSON字符串我加了一個,但我不知道這是多麼有用。我提供的代碼正確解析並返回這些數據。我只是不確定它是否是最優化/有效的方式,因爲我對Android開發比較陌生。只是尋找一些反饋! – leerob 2015-04-02 04:01:35

+0

我相信Gson最好是在Json上操作,並且結合凌空的事情變得相當容易 – 2015-04-02 04:04:52

回答

0

@leerob你好,在同一時間,我發現自己在你身在何處左右爲難,但最近我已經使用的基礎類,使得Android成爲處理JSON和是相當不錯的,一個很好的做法,我建議你的是申報JSON的鍵常量,我分享了一個例子:

public void insertMovieTypeFromJson(String movieTypeJsonStr) throws JSONException { 
      final String ID = "id"; 
      final String TYPE = "type"; 
      final String DESCRIPTION = "description"; 

      if (movieTypeJsonStr == null) 
        return; 

      try { 
        JSONArray movieTypeArrayJson = new JSONArray(movieTypeJsonStr); 

        Vector<ContentValues> cVVector = new Vector<>(movieTypeArrayJson.length()); 

        for (int i = 0; i < movieTypeArrayJson.length(); i++) { 

          long id; 
          String type; 
          String description; 

          JSONObject movie = movieTypeArrayJson.getJSONObject(i); 

          id = movie.getLong(ID); 
          type = movie.getString(TYPE); 
          description = movie.getString(DESCRIPTION); 

          ContentValues movieTypeValues = new ContentValues(); 

          movieTypeValues.put(MovieContract.MovieTypeEntry._ID, id); 
          movieTypeValues.put(MovieContract.MovieTypeEntry.COLUMN_TYPE, type); 
          movieTypeValues.put(MovieContract.MovieTypeEntry.COLUMN_DESCRIPTION, description); 
          cVVector.add(movieTypeValues); 
        } 

        int inserted = 0; 

        if (cVVector.size() > 0) { 
          ContentValues[] cvArray = new ContentValues[cVVector.size()]; 
          cVVector.toArray(cvArray); 
          inserted = getContext().getContentResolver().bulkInsert(MovieContract.MovieTypeEntry.CONTENT_URI, cvArray); 
        } 

        Log.d(LOG_TAG, "MovieTask Complete. " + inserted + " MovieType Inserted"); 

      } catch (JSONException e) { 
        Log.e(LOG_TAG, e.getMessage(), e); 
        e.printStackTrace(); 
      } 
    } 

JSON:

[ 
    { 
     "id": "1", 
     "type": "Action & Adventure", 
     "description": "Action & Adventure" 
    }, 
    { 
     "id": "2", 
     "type": "Animation", 
     "description": "Animation" 
    }, 
    { 
     "id": "3", 
     "type": "Comedy", 
     "description": "Comedy" 
    }, 
    { 
     "id": "4", 
     "type": "Terror", 
     "description": "Terror" 
    } 
] 

我希望你覺得它有用。

0

嘗試......

private class TestJSONParsing extends AsyncTask<JSONArray, Void, JSONArray> 
{ 
    ArrayList<HashMap<String, String>> arraylist; 
    HashMap<String, String> map; 

    @Override 
    protected void onPreExecute() 
    { 
     super.onPreExecute(); 
     mProgressDialog = new ProgressDialog(MapActivity.this); 
     mProgressDialog.setTitle("Downloading Data"); 
     mProgressDialog.setMessage("Loading..."); 
     mProgressDialog.setIndeterminate(false); 
     mProgressDialog.show(); 

    } 

    @Override 
    protected JSONArray doInBackground(JSONArray... params) 
    { 
     return JSONFunctions.getJSONfromURL("myurl"); 

    } 

    @Override 
    protected void onPostExecute(JSONArray resultArray) 
    { 
     super.onPostExecute(resultArray); 
     mProgressDialog.dismiss(); 
     if (null != resultArray) 
     { 
      int resultLength = resultArray.length(); 
      if (resultLength > 0) 
      { 
       try 
       { 
        for (int i = 0; i < resultLength; i++) 
        { 
         JSONObject jsonObject = resultArray 
           .getJSONObject(i); 
         map.put("id", String.valueOf(i)); 
         map.put("name", jsonObject.getString("name")); 
         arraylist.add(map); 
        } 
       } catch (Exception e) 
       { 
        // TODO: handle exception 
        e.printStackTrace(); 
       } 

       if (arraylist.size() > 0) 
       { 
        SimpleAdapter adapter = new SimpleAdapter(
          MapActivity.this, arraylist, 
          R.layout.your_simple_row, new String[] 
          { "id", "name" }, new int[] 
          { R.id.nameId, R.id.name }); 
        // bind adapter to your components 
        listView.setAdapter(adapter); 
       } 
      } 
     } else 
     { 
      Toast.makeText(getApplicationContext(), "No data", 
        Toast.LENGTH_SHORT).show(); 
     } 

    } 

} 

快樂編碼...