[英]creating complex JSON using BasicNameValuePair
如何使用ArrayList創建此JSON以在Android中發布JSON
{
"user" :
{
"nickname" : "nickname6",
"password" : "1234",
}
}
我只得到一個平面JSON
ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nickname","nickname6"));
nameValuePairs.add(new BasicNameValuePair("password", "1234"));
您需要創建一個JSON,為此您必須將該JSON作為參數添加到POST方法中。 為此,您可以嘗試以下操作:
JSONObject json = new JSONObject(jsonString);
JSONObject joParams = json.getJSONObject("params");
String nickname = joParams.getString("nickname");
post.add(new BasicNameValuePair("nickname", nickname);
如您所知,HttpClasses,NameValuePair和BasicNameValuePair在最新的android中已被棄用。 我們現在應該避免它。
如果要創建
{
"user":{
"nickname":"nickname6"
"password":"1234",
}
}
比起下面的代碼示例,您可以使用JSONObject類創建相同的json。
JSONObject jObj = new JSONObject();
try {
JSONObject userCredentials = new JSONObject();
userCredentials.put("nickname","nickname6");
userCredentials.put("password","1234");
jObj.put("user", userCredentials);
} catch(Exception e) {
e.printStackTrace();
}
嘗試像這樣使用ContentValues
ContentValues values=new ContentValues();
values.put("username",name);
values.put("password",password);
或使用MultipartEntity
MultipartEntity multi = new MultipartEntity();
multi.addPart("name", new StringBody("your data"));
multi.addPart("Id", new StringBody("123"));
這是使用AsyncTask的http帖子示例:
public class httpSendrequest extends AsyncTask<Void,Void,String> {
ArrayList<NameValuePair> nvPairs=new ArrayList<>();
Boolean error=false;
@Override
protected void onPreExecute() {
super.onPreExecute();
//here you initialize your json object and add it to value pairs
JSONObject jObj = new JSONObject();
try {
JSONObject userCredentials = new JSONObject();
userCredentials.put("nickname","nickname6");
userCredentials.put("password","1234");
jObj.put("user", userCredentials);
nvPairs.add(new BasicNameValuePair("jsonstring",jObj.toString()));
} catch(Exception e) {
error=true;
}
}
@Override
protected String doInBackground(Void... params) {
if(!error)
try{
String link ="http://"+ip+"/QSystem.asmx/insert_answer" ;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link); //adding URL to the http post
httppost.setEntity(new UrlEncodedFormEntity(nvPairs, HTTP.UTF_8)); //adding the value pairs and encoding to the http post request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
} catch (Exception e){
error=true;
}
return "str";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(!error) {
Toast.makeText(getApplicationContext(), "Sent", Toast.LENGTH_SHORT).show();
}
}
}
那么您可以從onCreate或在OnClickListener中為按鈕調用它,如下所示:
new httpSendrequest().execute();
希望這可以幫助 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.