我知道这是一个奇怪的问题,但我需要一件事:我收到一个字符串作为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;
}
}
答案 0 :(得分:5)
尝试使用以下代码(stringArray
包含“数组”的String
代码:
ArrayList<String> myList = new ArrayList<String>(Arrays.asList(stringArray.substring(1, stringArray.length() - 1).replaceAll("\"", "").split(",")));
这将删除第一个和最后一个字符(分别为[
和]
)并按,
字符拆分。然后,使用ArrayList
方法将其转换为Arrays.asList
。
答案 1 :(得分:1)
您可以遍历JSONArray
并将其添加到ArrayList
。
ArrayList<String> list = new ArrayList<String>();
JSONArray jr = new JSONArray("string");
for(int i=0;i<jr.length();i++)
{
String value =(String) jr.get(i);
list.add(value);
}
但是您没有使用Thread
或Asynctask
从服务器获取json。不要在生产阶段使用StrictMode
。
同时检查清单@SuppressLint({ "NewApi", "NewApi", "NewApi" })
中的minsdk。你已经压制了lint警告