我有一个类型" String"的ArrayList;包含某些值。我想使用Web服务将此ArrayList发送到远程数据库。我计划使用JSON插入相同的内容,但我遇到了一些困难,并且想要了解它。
这是我目前的代码:
我的ArrayList定义如下。它的目的是存储复选框值
ArrayList<String> items2 = new ArrayList<String>();
for (int i = 0; i < arr2.length; i++)
{
if (checkedabsent.get(i))
{
items2.add(arr2[i]); //arr2 is a String array containing all values
System.out.println(items2);
}
}
Log.d("", "items:");
for (String string : items2)
{
Log.d("", string);
System.out.println(items2);
}
这是我发现的难啊!! JSON代码
HttpPost httppost = new HttpPost("http://10.0.2.2/enterdata/Service1.asmx");
HttpClient client = new DefaultHttpClient(httpParams);
try
{
String result;
JSONObject obj = new JSONObject();
// how do I put the array list over here ??
int TIMEOUT_MILLISEC = 10000; // = 10 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader("Accept","application/json");
// Execute HTTP Post Request
HttpResponse httpResponse = client.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null)
{
InputStream is = httpEntity.getContent();
result = is.toString();
Log.i("Result is ", "Result: " + result);
if(result.equalsIgnoreCase("success"))
{
startActivity(new Intent(Mark.this,nextscreen.class));
}
}
}
答案 0 :(得分:4)
要转换为JSON数组,请使用以下
ArrayList<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
JSONArray jsArray = new JSONArray(list);
然后传递jsArray
,如described here。
很抱歉,如果我误解了你的问题。
更新,所以:
ArrayList<String> items2 = new ArrayList<String>();
for (int i = 0; i < arr2.length; i++)
{
if (checkedabsent.get(i))
{
items2.add(arr2[i]); //arr2 is a String array containing all values
System.out.println(items2);
}
}
Log.d("", "items:");
for (String string : items2)
{
Log.d("", string);
System.out.println(items2);
}
HttpPost httppost = new HttpPost("http://10.0.2.2/enterdata/Service1.asmx");
HttpClient client = new DefaultHttpClient(httpParams);
try
{
String result;
//JSONObject obj = new JSONObject();
JSONArray jsArray = new JSONArray(items2);
int TIMEOUT_MILLISEC = 10000; // = 10 seconds
HttpParams httpParams = new BasicHttpParams();
...
答案 1 :(得分:1)
你能这样做吗?
ArrayList<String> items2 = new ArrayList<String>();
...
JSONObject obj = new JSONObject();
for(int i=0; i<items2.size(); i++)
{
obj.put("" + i, items.get(i));
}
//then use obj.write(Writer x) to send it
答案 2 :(得分:1)
您可以从JSONArray
ArrayList
JSONArray foo = new JSONArray(yourArrayList);