Comment envoyer les données de plusieurs objects json au serveur dans Android?

Comment envoyer plusieurs valeurs json au serveur.

public class UserVO { private Ssortingng userId; private Ssortingng firstName; private Ssortingng lastName; private Ssortingng mobileNumber; private Ssortingng stdCode; private Ssortingng landlineNumber; private Ssortingng countryCode; private Ssortingng stateCode; private Ssortingng zipcode; private Ssortingng status; private LoginVO loginVO; private AddressVO addressVO; private proofVO proofVO VO; } 

J’ai implémenté comme ça.

 next_Edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new CreateUser().execute(); } }); class CreateUser extends AsyncTask { int success=0; JSONObject json; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(ConsentActivity.this); pDialog.setMessage("Registering New User.."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected Ssortingng doInBackground(Ssortingng... args) { SharedPreferences pref = getSharedPreferences("UserMgmt", Context.MODE_PRIVATE); Ssortingng Firstname = pref.getSsortingng("FName", ""); Ssortingng Lastname = pref.getSsortingng("LName", ""); Ssortingng Userid = pref.getSsortingng("UserId", ""); Ssortingng Password = pref.getSsortingng("Password", ""); Ssortingng Repassword = pref.getSsortingng("RePassword", ""); Ssortingng Idproof_typ=pref.getSsortingng("IdType",""); Ssortingng Idproof_number=pref.getSsortingng("IdNumber",""); Ssortingng Dob=pref.getSsortingng("DOB",""); Ssortingng Gender=pref.getSsortingng("Gender",""); Ssortingng Email=pref.getSsortingng("Email",""); Ssortingng Mobile_number=pref.getSsortingng("Mobile",""); Ssortingng Country_code=pref.getSsortingng("CountryCode",""); Ssortingng Landline=pref.getSsortingng("LandLine",""); Ssortingng Country=pref.getSsortingng("Country",""); Ssortingng State=pref.getSsortingng("State",""); Ssortingng Address=pref.getSsortingng("Address",""); Ssortingng Pincod=pref.getSsortingng("Pincode",""); boolean Tc_chk_state = pref.getBoolean("ChkBoxTC", true); Ssortingng status_tc_chk=Ssortingng.valueOf(Tc_chk_state); Ssortingng status_tc=status_tc_chk.subssortingng(0,1); boolean Consent_chk_state = pref.getBoolean("ChkBoxConsent", true); Ssortingng status_con_chk=Ssortingng.valueOf(Tc_chk_state); Ssortingng status_con=status_con_chk.subssortingng(0,1); List params = new ArrayList(); params.add(new BasicNameValuePair("userId", Userid)); params.add(new BasicNameValuePair("firstName", Firstname)); params.add(new BasicNameValuePair("lastName", Lastname)); params.add(new BasicNameValuePair("identityType", Idproof_typ)); params.add(new BasicNameValuePair("identityNumber", Idproof_number)); params.add(new BasicNameValuePair("dob", Dob)); params.add(new BasicNameValuePair("gender", Gender)); params.add(new BasicNameValuePair("emailId", Email)); params.add(new BasicNameValuePair("mobileNumber", Mobile_number)); params.add(new BasicNameValuePair("stdCode", Country_code)); params.add(new BasicNameValuePair("landlineNumber", Landline)); params.add(new BasicNameValuePair("countryCode", Country)); params.add(new BasicNameValuePair("stateCode", State)); params.add(new BasicNameValuePair("zipcode", Pincod)); params.add(new BasicNameValuePair("status", status_tc)); params.add(new BasicNameValuePair("password", Password)); params.add(new BasicNameValuePair("address", Address)); /*json = jsonParser.makeHttpRequest(url_new_user, "POST",params);*/ // Log.d("Create Response", json.toSsortingng()); JSONArray jsonArray = new JSONArray(); final JSONObject json = new JSONObject(); final JSONObject login = new JSONObject(); final JSONObject address = new JSONObject(); final JSONObject identity = new JSONObject(); HttpResponse response; HttpClient client = new DefaultHttpClient(); HttpContext httpContext = new BasicHttpContext(); HttpPost post = new HttpPost("http://191.121.1.145:8080/medicine/services/users/createUser"); post.setHeader("Content-type", "application/json"); try { Log.e("userId",Userid); Log.e("firstName",Firstname); Log.e("lastName",Lastname); Log.e("emailId",Email); Log.e("password",Password); Log.e("newPassword",Repassword); Log.e("status",status_tc); json.put("userId", Userid); json.put("firstName", Firstname); json.put("lastName", Lastname); //json.put("identityType",Idproof_typ); //json.put("identityNumber",Idproof_number); json.put("dob",Dob); json.put("gender",Gender); json.put("emailId", Email); json.put("mobileNumber",Mobile_number); json.put("stdCode",Country_code); json.put("landlineNumber",Landline); json.put("countryCode",Country); json.put("stateCode",State); json.put("zipcode",Pincod); json.put("status",status_tc); //json.put("password",Password); // json.put("address",Address); jsonArray.put(json); try{ login.put("password",Password); jsonArray.put(login); }catch(Exception exception){ exception.printStackTrace(); } try{ address.put("address",Address); jsonArray.put(address); }catch(Exception exception){ exception.printStackTrace(); } try{ identity.put("identityType",Idproof_typ); identity.put("identityNumber",Idproof_number); jsonArray.put(identity); }catch(Exception exception){ exception.printStackTrace(); } SsortingngEntity se = new SsortingngEntity( jsonArray.toSsortingng()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); response = client.execute(post); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 201){ Log.e("Responce","OK"); } } catch(Exception e) { e.printStackTrace(); //Toast.makeText(getApplicationContext(), "establishment with server failed", Toast.LENGTH_LONG).show(); // createDialog("Error", "Cannot Estabilish Connection"); } /*try { success = json.getInt(TAG_SUCCESS); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); }*/ return null; } protected void onProgressUpdate(Integer... progress) { } protected void onPostExecute(Ssortingng file_url) { // dismiss the dialog once done pDialog.dismiss(); /* try { int success = json.getInt(TAG_SUCCESS);*/ if (success == 1) { // successfully created a user Intent i = new Intent(getApplicationContext(), LoginActivity.class); startActivity(i); // closing this screen finish(); } /*else { // failed to create user // Log.d("failed to create user", json.toSsortingng()); }*/ /*} catch (JSONException e) { e.printStackTrace(); }*/ } } 

Ici, jusqu’à l’état est des valeurs directes, à l’intérieur de userVO trois autres VO sont là comme loginVO, AddressVO, proofVO.

Avec ces classes VO, 5 valeurs sont présentes.

Maintenant, comment envoyer ces informations au serveur en utilisant la méthode POST. Je suis totalement confus.

Pouvez-vous s’il vous plaît donner une solution claire à ce sujet?

Vous pouvez envoyer des données en utilisant la méthode HTTP post.

  public void postData(){ // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.yourdomain.com/post.php"); try { // Add your data List nameValuePairs = new ArrayList(1); // Your user variable which are directly send from here nameValuePairs.add(new BasicNameValuePair("data1", "dataValue")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(20); int current = 0; while((current = bis.read()) != -1){ baf.append((byte)current); } /* Convert the Bytes read to a Ssortingng. */ text = new Ssortingng(baf.toByteArray()); txtvw.setText(text); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } 

Vous pouvez trouver un tutoriel complet pour cela sur ce lien https://fahmirahman.wordpress.com/2011/04/26/the-simplest-way-to-post-parameters-between-android-and-php/

Aussi, je vous recommande d’utiliser la bibliothèque de réseau ION qui est très facile.

https://github.com/koush/ion

Vous trouverez toutes les informations dont vous avez besoin.

Pour convertir des objects dans le JSON, vous pouvez utiliser la bibliothèque GSON .

Gson est une bibliothèque Java pouvant être utilisée pour convertir des objects Java en leur représentation JSON. Il peut également être utilisé pour convertir une chaîne JSON en un object Java équivalent.

Pas:

  1. Il suffit d’utiliser la bibliothèque GSON et de convertir vos objects en JSON
  2. Convertir le JSON dans la chaîne
  3. Publiez la chaîne en utilisant HTTPPost

Vous devez l’envoyer en tant que HTTP. Les messages HTTP sont envoyés sous forme de texte. Vous devez donc créer une représentation sous forme de chaîne de votre object JSON. Quelque chose comme

 { UserVO: { userId: "", firstName: "" } } 

Avez-vous essayé avec la paire Name Value ??? sinon essayez d’utiliser mon code suivant

 HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("url"); List value = new ArrayList(); value.add(new BasicNameValuePair("userid", userId)); //the userid which is inside the "" is server variable //Form as like above for all variable then use below line of code to get response post.setEntity(new UrlEncodedFormEntity(name)); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); Ssortingng line = ""; SsortingngBuilder sb = new SsortingngBuilder(); while ((line = rd.readLine()) != null) { sb.append(line + "\n"); } Ssortingng result = sb.toSsortingng(); 

Si vous avez besoin d’aide, faites un commentaire