1

I am working on web services in android,
i have three strings

String username = "Rajesh";
String password = "abc"
String usertype = "member";

and i want to send them to web service in the following form

 {"UserName":username,"Password":password,"UserType":usertype}  

like

 {"UserName":"Rajesh","Password":"abc","UserType":"member"}

web service url is something like : http://abc.xyz.org/api/login

i dont have any idea how to do it, please help me,
how can i convert strings to json like above and how can i pass it to web service
Thank you

Rajesh Panchal
  • 1,140
  • 3
  • 20
  • 39

3 Answers3

1

You can try this, JSONObject.put() uses a key value pair so do as needed:

try {
    JSONObject object = new JSONObject();
    object.put("username", "rajesh");
    object.put("password", "password");
} catch (JSONException e) {
    e.printStackTrace();
}

After forming the required JSONObject you can use HttpClient to send it onto a request, refer here.

You can also refer to my project on making Http requests on android here.

Community
  • 1
  • 1
Rakeeb Rajbhandari
  • 5,043
  • 6
  • 43
  • 74
1

Yes, You can use by Json Object Like below,

JSONObject jsonObj = new JSONObject();
jsonObj.put("UserName", "Rajesh"); 
jsonObj.put("Password", "abc");
jsonObj.put("UserType", "member");

If you send In webservice then

String json = jsonObj.toString();

StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);

also check pass json object in url

Divyang Metaliya
  • 1,908
  • 1
  • 12
  • 14
1
package com.aven.qqdemo;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonUutis {

private void toWebService(){
    JSONObject json = new JSONObject();
    String username = "Rajesh";
    String password = "abc";
    String usertype = "member";
    putJson(json,"UserName", username);
    putJson(json,"Password", password);
    putJson(json,"UserType", usertype);
    String jsonString = json.toString();
    //Send jsonString to web service.
}

private void putJson(JSONObject json, String key, String value){
    try {
        json.put(key, value);
    } catch (JSONException e) {
        //Error happened.
    }
}

}

Field.wei
  • 69
  • 5