2015-04-02 35 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(); 
     } 

    } 

} 

快乐编码...