我知道这是一个奇怪的问题,但我需要一件事:我收到一个字符串作为 http 操作的结果。实际上,这个字符串包含一个字符串数组,如下所示:
["Leon","Prova 2","TestData"]
基本上我想将此字符串转换为 ArrayList,因为我需要它作为适配器。这是java代码:
public class Archivio{
static ArrayList<String> titoli = new ArrayList<String>();
static ArrayList<String> art = new ArrayList<String>();
static String response, response2 = null;
HttpClient httpclient;
HttpPost httppost,httppost2;
List<NameValuePair> nameValuePairs,namePairs;
@SuppressLint({ "NewApi", "NewApi", "NewApi" })
Archivio() {
try {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://tripleleon.altervista.org/artiview2.php");
nameValuePairs = new ArrayList<NameValuePair>();
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Esecuzione richiesta HTTP Post e ricezione risultato operazione
//response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
httppost2= new HttpPost("http://tripleleon.altervista.org/artiview3.php");
namePairs = new ArrayList<NameValuePair>();
httppost2.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler2 = new BasicResponseHandler();
response2 = httpclient.execute(httppost2, responseHandler2);
System.out.println("Response : " + response2);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ArrayList<String> retTitle() {
return response;
}
ArrayList<String> retArt() {
return response2;
}
}
最佳答案
尝试使用以下代码(作为 stringArray
包含您的“数组”的 String
):
ArrayList<String> myList = new ArrayList<String>(Arrays.asList(stringArray.substring(1, stringArray.length() - 1).replaceAll("\"", "").split(",")));
这将删除第一个和最后一个字符(分别为 [
和 ]
)并用 ,
字符分隔。然后,使用 Arrays.asList
方法将其转换为 ArrayList
。
关于android - 将字符串转换为 ArrayList<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22864846/