2011-11-23 129 views
0

我使用json解析一個url。我將得到每個標籤的值,並使用getString中的for -loop將其存儲在字符串中。如何將字符串中存儲的數據轉換爲字符串數組

我想要的是將String值存儲到String數組中。就Android開發而言,我是一個小菜鳥。

下面是代碼:

JSONObject json = JsonFunctions.getJSONfromURL("http://www.skytel.mobi/stepheniphone/iphone/stephenFlickr.json"); 

try { 
    JSONArray boombaby=json.getJSONArray("items"); 

    for(int i=0;i<boombaby.length();i++) { 
    JSONObject e = boombaby.getJSONObject(i); 
    mTitleName=e.getString("title"); 
    String mTitleImage=e.getString("image"); 
    } 
} 
+0

現在你甚至沒有存儲在您每次創建新的字符串和地方投擲另一個在內存中,直到GC拿起它:) – doNotCheckMyBlog

回答

3

使用列表來存儲您的標題,另一個儲存圖像。或設計這個類中的一個拿着兩個字段(標題和圖片),並存儲在實例列表:

List<String> titles = new ArrayList<String>(); 
List<String> images = new ArrayList<String>(); 
for (int i = 0; i < boombaby.length(); i++) { 
    JSONObject e = boombaby.getJSONObject(i); 
    titles.add(e.getString("title")); 
    images.add(e.getString("image")); 
} 

閱讀Java tutorial about collections。這是一個必須知道的。

+0

我把它存儲在arrayllist中,它工作正常..但我想要的是將其存儲在字符串數組.. ..它以任何方式... – kingston

+0

如何使用HashMap 標題可以是關鍵和價值形象! :) – doNotCheckMyBlog

+0

打開javadoc並讀取ArrayList具有的不同方法,您可以通過images.toArray()輕鬆轉換爲數組。 – doNotCheckMyBlog

1

我的解決辦法:

String[] convert2StringArr(String str) 
{ 
    if(str!=null&&str.length()>0) 
    { 
     String[] arr=new String[str.length()]; 
     for(int i=0;i<str.length();i++) 
     { 
      arr[i]=new String(str.charAt(i)+""); 
     } 
     return arr; 
    } 
    return null; 
} 
+0

這將字符串轉換爲其字符的字符串數組。這對OP沒有幫助。 – st0le

0
List<String> titles = new ArrayList<String>(); 
List<String> images = new ArrayList<String>(); 
for (int i = 0; i < boombaby.length(); i++) { 
    JSONObject e = boombaby.getJSONObject(i); 
    titles.add(e.getString("title")); 
    images.add(e.getString("image")); 
} 

,然後轉換列表數組:

String[] titleArray = (String[])titles.toArray(new titles[titles.size()]); 

String[] imageArray = (String[])images.toArray(new titles[images.size()]); 
相關問題