2012-07-11 89 views
0

這裏我再起來代碼:解析來自web服務的一個JSON文件與Android

我的新的解析器至極返回JSONArray:

public class JsonParser2 { 

static InputStream is = null; 
static JSONObject jObj = null; 
static String jsonstr = ""; 

// constructor 
public JsonParser2() { 
} 

public JSONArray getJSONFromUrl(String url) { 

    // Making HTTP request 
    try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 
     //HttpGet httpGet = new HttpGet(url); 

     //HttpResponse httpResponse = httpClient.execute(httpGet); 
     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent();   

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

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "n"); 
     } 
     is.close(); 
     jsonstr = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 
    JSONArray jArray = null; 
// try parse the string to a JSON array 
    try { 
     jArray = new JSONArray(jsonstr); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing de Mon fichier: " + e.toString()); 
    } 
    return jArray; 

} }

這裏我的活動(工作正常):

public class AndroidJSONParsingActivity extends ListActivity 

{

// url to make request 
private static String url = "http://developer.prixo.fr/API/GetEvents?zone=8"; 

//JSON names 
private static final String TAG_content = "content"; 
private static final String TAG_zone = "zone"; 
private static final String TAG_id = "id"; 
private static final String TAG_area = "area"; 
private static final String TAG_title = "title"; 
private static final String TAG_date = "date"; 
private static final String TAG_author = "author"; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    // Hashmap for ListView 
    ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>(); 

    // Creating JSON Parser instance 
    JsonParser2 jParser = new JsonParser2(); 

    // getting JSON string from URL 
    JSONArray json = jParser.getJSONFromUrl(url); 

    try { 
      for(int i=0; i < json.length(); i++) 
      { 
       JSONObject child = json.getJSONObject(i); 

       String id = child.getString(TAG_id); 
       String title = child.getString(TAG_title); 
       String content = child.getString(TAG_content); 
       String date = child.getString(TAG_date); 
       String author = child.getString(TAG_author); 
       String zone = child.getString(TAG_zone); 
       String area = child.getString(TAG_area); 


       // creating new HashMap 
       HashMap<String, String> map = new HashMap<String, String>(); 

       // adding each child node to HashMap key => value 
       map.put(TAG_content, content); 
       map.put(TAG_title, title); 
       map.put(TAG_author, author); 

       // adding HashList to ArrayList 
       newsList.add(map); 
      } 
     } 
    catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    /** 
    * Updating parsed JSON data into ListView 
    * */ 
    ListAdapter adapter = new SimpleAdapter(this, newsList,R.layout.list_item,new String[] { TAG_content, TAG_title, TAG_author }, new int[] {R.id.name, R.id.email, R.id.mobile }); 
    setListAdapter(adapter); 

    // selecting single ListView item 
    ListView lv = getListView(); 

    // Launching new screen on Selecting Single ListItem 
    lv.setOnItemClickListener(new OnItemClickListener() 
    { 
     public void onItemClick(AdapterView<?> parent, View view,int position, long id) { 
      // getting values from selected ListItem 
      String name = ((TextView) view.findViewById(R.id.name)).getText().toString(); 
      String cost = ((TextView) view.findViewById(R.id.email)).getText().toString(); 
      String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString(); 

      // Starting new intent 
      Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class); 
      in.putExtra(TAG_content, name); 
      in.putExtra(TAG_title, cost); 
      in.putExtra(TAG_author, description); 
      startActivity(in); 

     } 
    }); 
} 

}

====>問題通過實施爲()與JSON子對象獲取每個信息解決! (代碼已上傳;))

+0

你真的獲得數據嗎?在將其轉換爲JSONObject之前,應該先打印出字符串,以確保其格式正確。 – javajavajava 2012-07-11 19:57:02

回答

2

這是因爲你的JSON定義了一個JSON數組,你試圖將它解析爲JSON對象 - 在你的解析器類中將其更改爲JSONArray,你應該沒問題。

另一個問題是memorz管理 - 您正在重新分配字符串並使用android提供的vanilla JSON解析器進行解析。這種方法很有效,但內存消耗很大,分配很多 - 對於更大的數據來說非常慢。使用拉解析器,而不是(像GSON,縮小版僅16K)

您也可以考慮一種數據綁定到創建Java對象了JSON的 - 你可以搶我的圖書館(也可在行家中心):

https://github.com/ko5tik/jsonserializer

那麼這將是容易,因爲:

 InputStream inputStream = getResources().openRawResource(preferences.getRecognitionConfig()); 
     InputStreamReader reader = new InputStreamReader(inputStream); 


     JsonReader jreader = new JsonReader(reader);   
     jreader.setLenient(true); 
     final RecognitionDataContainer recognitionContainer = JSONUnmarshaller.unmarshall(jreader, RecognitionDataContainer.class); 

     reader.close(); 

(RecognitionDataContainer是類似於JSON結構的頂層對象)

+0

你能告訴我什麼我必須改變我的代碼來解析我的方法嗎? :$ – eento 2012-07-11 21:20:19

+0

Konstantin,我無法直接下載你的jasonserializer.jar(找不到文件)。現在我有了這種感覺:用我的方法「android.os.networkonmainthreadexception」..如果你能幫助我在你的優化版本中實現同樣的東西,那對我應該沒問題。謝謝 – eento 2012-07-12 08:37:43

+0

它可以從maven中央倉庫獲得:http://mvnrepository.com/artifact/de.pribluda.android/jsonmarshaller/0.6答:在主UI線程上從網絡讀取是不明智的 - 你會阻止前端,android是一般反對這種濫用。剛開始後臺線程並閱讀 – 2012-07-12 16:18:50