2011-07-13 93 views
-1

字符串數組我在遇到此JSON反序列化的煩惱:JSON來使用GSON

[{"categorium": 
    {"created_at":"2011-06-09T08:57:41Z","c1":"rete stradale","updated_at":"2011-06-09T08:57:41Z","id":1}}, 
    {"categorium":{"created_at":"2011-06-09T13:50:29Z","c1":"servizi pubblici","updated_at":"2011-06-09T13:50:29Z","id":2}}, 
    {"categorium":{"created_at":"2011-06-09T13:50:37Z","c1":"illuminazione","updated_at":"2011-06-09T13:50:37Z","id":3}}, 
    {"categorium":{"created_at":"2011-06-09T13:50:46Z","c1":"inquinamento","updated_at":"2011-06-09T13:50:46Z","id":4}} 
] 

我如何可以推斷所有的「C1」的屬性,所以我可以返回他們的字符串數組?

* UPDATE:解決方案*

public class getElements { 

String [] getEl (String url) throws ClientProtocolException, IOException { 

    Categoria c = null; 
    Categoria[] cArray = null; 
    String [] c1Array = null; 
    HttpClient client = new DefaultHttpClient(); 
    HttpGet request = new HttpGet("http://10.0.2.2:3000/"+url); 

    HttpResponse response = client.execute(request); 
    HttpEntity entity = response.getEntity(); 
    String stringa = "{\"categorium\":{\"created_at\":\"2011-06-09T08:57:41Z\",\"c1\":\"rete stradale\",\"updated_at\":\"2011-06-09T08:57:41Z\",\"id\":1}}"; 

    Gson json=new Gson(); 
     try{ 
      cArray=json.fromJson(stringa, Categoria[].class); 
      Log.i("ELEMENTO", ""+cArray); 
     }catch(JsonParseException e){ 
      Log.i("error","JsonParseException"); 
     } 

     c1Array = new String[cArray.length]; 
     for (int i=0; i<cArray.length; i++) { 
      c1Array[i] = cArray[i].c1; 
     } 

    return c1Array; 


} 
} 

Categorium類:

public class Categoria { 
    public String created_at; 
    public String c1; 
    public String updated_at; 
    public int id; 

    public Categoria() { 
     this.created_at = ""; 
     this.c1=""; 
     this.updated_at = ""; 
     this.id = 0; 
    } 

} 
+0

爲什麼不能讀取所有Categoria對象,然後手動創建一個簡單循環中的c1元素數組? – bezmax

+0

我如何閱讀所有這些內容?隨着我寫的代碼,我只拿一個c1,對吧?順便說一句... logcat給我一個JsonParseException:「entity.toString」是在字符串類型中獲取Json的正確方法? –

+0

啊,現在我明白了:) – bezmax

回答

0

反序列化數組使用此代碼:

Categorium[] cArray = null; 
cArray = gson.fromJson(stringa, Categorium[].class); 

然後讓所有的C1的:

String[] c1Array = new String[cArray.length]; 
for (int i=0; i<cArray.length; i++) { 
    c1Array[i] = cArray[i].c1; 
}