2012-06-10 37 views
0

的等效名單,我可以使用下面的代碼如何將這個JSON字符串轉換爲

HttpClient client = new DefaultHttpClient(); 
    HttpGet httpGet = new HttpGet(
      URL.toString()); 




    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)); 

      finalResult.setText("Done") ; 

      Result = reader.readLine(); 


     } else { 
      Result = "error"; 
     } 
    } catch (ClientProtocolException e) { 
     Result = "error"; 
     e.printStackTrace(); 
    } catch (IOException e) { 
     Result = "error"; 
     e.printStackTrace(); 
    } 

解析簡單的JSON字符串,但現在我有以下的JSON字符串

[{"Name":"Ali" ,"Age":35,"Address":"cccccccccccc"} ,{"Name":"Ali1" ,"Age":351,"Address":"cccccccccccc1"} , 
{"Name":"Ali2" ,"Age":352,"Address":"cccccccccccc2"} 
] 

和階級代表它

package com.appnetics; 

import android.R.string; 

public class Encounter { 
    public string Name; 
    public string Address; 
    public int Age; 
} 

我想遍歷這個JSON並將其轉換爲list<Encounter>

任何想法如何做到這一點

回答

3

使用org.json命名空間。爲了您的具體的例子,你可以這樣做:

ArrayList<Encounter> encounters=new ArrayList<Encounter>(); 
JSONArray array=new JSONArray(Result); 
for(int i=0;i<array.length();i++){ 
    JSONObject elem=(JSONObject)array.get(i); 
    Encounter encounter=new Encounter(); 
    Encounter.Name=elem.getString("Name"); 
    Encounter.Age=elem.getInt("Age"); 
    Encounter.Address=elem.getString("Address"); 
    encounters.add(encounter); 
} 
+0

答案是100%正確的。如果作者有更多的序列化/反序列化到JSON的類,我會建議他看看Gson庫 - https://sites.google.com/site/gson/gson-user-guide –

3

另一種更簡單的方法是使用Gson another lib來緩解你的實現是更容易比自帶的Android平臺org.json實現作爲使用。

如果您確定域對象。然後,你只有兩行代碼來解析JSON ......像

Gson gson = new Gson(); 
YourDomainObject obj2 = (YourDomainObject) gson.fromJson(jsonString, 
    YourDomainObject.class); 

,它可以處理集合n的所有了。