How to set header in Android Json - android

I want to fetch data from the Web service HttpGet Method. Web Service needs two header information.
How can i add set Parameters ?
"Content-Type", "application/json"
"Authorization", "Bearer " + Utils.PreferencesGetir(ActivityPuanlarim.this, "Preferences_Token"))
Json Data
[
{
"ID": 12,
"KayitTarihi": "2016-07-21T08:37:01.603",
"KullanilanPuan": 0,
"KuponID": 2,
"KuponKullanim": [],
"KuponNo": "S7240061",
"KuponAciklama": "Açıklama 1",
"Puan": 40
},
{
"ID": 13,
"KayitTarihi": "2016-07-21T09:38:48.877",
"KullanilanPuan": 0,
"KuponID": 2,
"KuponKullanim": [],
"KuponNo": "S7240071",
"KuponAciklama": "Açıklama 2",
"Puan": 40
}
]
AsyncTask doInBackground
#Override
protected Void doInBackground(Void... voids) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Content-Type", "application/json"));
params.add(new BasicNameValuePair("Authorization", "Bearer " + Utils.PreferencesGetir(ActivityPuanlarim.this, "Preferences_Token")));
JSONArray json = jParser.makeHttpRequestArray(URL, "GET", params);
try {
if (Utils.InternetKontrol(ActivityPuanlarim.this) == true) {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
String id = c.getString("ID");
String kayitTarihi = c.getString("KayitTarihi");
String kullanilanPuan = c.getString("KullanilanPuan");
String kuponID = c.getString("KuponID");
String kuponKullanim = c.getString("KuponKullanim");
String kuponNo = c.getString("KuponNo");
String kuponAciklama = c.getString("KuponAciklama");
String puan = c.getString("Puan");
// Hashmap oluşturulur
HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", id);
map.put("KayitTarihi", kayitTarihi);
map.put("KullanilanPuan", kullanilanPuan);
map.put("KuponID", kuponID);
map.put("KuponKullanim", kuponKullanim);
map.put("KuponNo", kuponNo);
map.put("KuponAciklama", kuponAciklama);
map.put("Puan", puan);
puanlarimTumKayitlarList.add(map);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

As you do not send a HttpRequest, you don't need these parameters. You should rather request content from Servlet via URLConnection and then read the data in your activity.
Example here:
https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
Edit:
I've read that you can use HttpGet in Activity like this:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("key", VALUE);
HttpResponse httpResponse = httpClient.execute(httpGet);

Related

How to fetch json array inside array in android listview

I'm having json format as below , How do i fetch it into listview in android, While i'm trying to do, following error rises. I,m having multiple starting array square brackets.
org.json.JSONException: Value [{"id":"30","title":"Android Design Engineer","postedDate":"2016-11-19","jobtype":"Contract","location":"Alabama","description":"Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world","experience":"2 to 6 yrs","salary":" Upto $50"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject
and the following my java code is, here i call jsosarray and split it into objects.
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String recode = String.valueOf(code);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(is));
json_result = bufferedReader.readLine();
try {
if (code == 200) {
JSONArray jsonArray = new JSONArray(json_result);
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject c = jsonArray.getJSONObject(i);
String id = c.getString(TAG_ID);
String jobname = c.getString(TAG_JOBTITLE);
String description = c.getString(TAG_DESC);
String jobtype = c.getString(TAG_JOBTYPE);
String salary = c.getString(TAG_SALARY);
String postedon = c.getString(TAG_POSTEDDATE);
String location = c.getString(TAG_LOCATION);
String exp = c.getString(TAG_EXPE);
HashMap<String, String> result = new HashMap<String, String>();
result.put(TAG_ID, id);
result.put(TAG_JOBTITLE, jobname);
result.put(TAG_DESC, description);
result.put(TAG_JOBTYPE, jobtype);
result.put(TAG_SALARY, salary);
result.put(TAG_POSTEDDATE,postedon);
result.put(TAG_LOCATION, location);
result.put(TAG_EXPE, exp);
resultList.add(result);
}
} else {
JSONObject jsonObj = new JSONObject(json_result);
status = jsonObj.getString("status");
msg = jsonObj.getString("msg");
}
return recode;
} catch (JSONException e) {
Log.e("Json erroe", e.toString());
return e.toString();
My Json array
[
[
{
"id": "30",
"title": "Android Design Engineer",
"description": "Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world",
"jobtype": "Contract",
"salary": " Upto $50",
"postedDate": "2016-11-19",
"location": "Alabama",
"experience": "2 to 6 yrs"
}
],
[
{
"id": "24",
"title": "Android Application Developer",
"description": "Android Application Developer is the major Development Technique that is used in this damn World.",
"jobtype": "Contract",
"salary": " Upto $50",
"postedDate": "2016-11-16",
"location": "North Carolina",
"experience": "6 to 10 yrs"
}
]
]
Check below parsing logic as per your JSON:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String recode = String.valueOf(code);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(is));
json_result = bufferedReader.readLine();
try {
if (code == 200) {
JSONArray jsonArray = new JSONArray(json_result);
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray jsonChildArray = jsonArray.getJSONArray(i);
if (jsonChildArray != null && jsonChildArray.length() > 0) {
JSONObject c = jsonChildArray.getJSONObject(0);
String id = c.getString(TAG_ID);
String jobname = c.getString(TAG_JOBTITLE);
String description = c.getString(TAG_DESC);
String jobtype = c.getString(TAG_JOBTYPE);
String salary = c.getString(TAG_SALARY);
String postedon = c.getString(TAG_POSTEDDATE);
String location = c.getString(TAG_LOCATION);
String exp = c.getString(TAG_EXPE);
HashMap<String, String> result = new HashMap<String, String>();
result.put(TAG_ID, id);
result.put(TAG_JOBTITLE, jobname);
result.put(TAG_DESC, description);
result.put(TAG_JOBTYPE, jobtype);
result.put(TAG_SALARY, salary);
result.put(TAG_POSTEDDATE, postedon);
result.put(TAG_LOCATION, location);
result.put(TAG_EXPE, exp);
resultList.add(result);
}
}
}
} else {
JSONObject jsonObj = new JSONObject(json_result);
status = jsonObj.getString("status");
msg = jsonObj.getString("msg");
}
return recode;
} catch (JSONException e) {
Log.e("Json erroe", e.toString());
return e.toString();
}
} catch (Exception e) {
Log.e("erroe", e.toString());
return e.toString();
}
Yes .There is an error.Your JSON Data has An array inside array and you are trying to assign internal array as object.
First convert outer array JsonArray jsonArray1;
Iterate through this array. i=0 -> jsonArray1.length; and create another
JsonArray jsonArray2 = jsonArray1[i];
And finally iterate through jsonArray2: j=0 -> jsonArray2.length()
and create a JsonObject json = jsonArray2[j];
I hope you understood. This is psuedocode. If you want code, tell me.I can write it.

How to get values from json webservices

Given below is my JSON response from web-service.
{"message":"success","data":[{"push_status":"1"}]}
I want to get the value of push_status from {"push_status":"1"}.
This is my code:
public static VehicleDetails getPushNotificationstatus(String clientCode, String secretode) throws ClientProtocolException,
IOException, JSONException {
Log.d(WebServiceHelper.TAG, "getPushNotificationstatus==============>");
VehicleDetails vdetails = null;
String result;
ArrayList<VehicleDetails> SIArrayList = new ArrayList<VehicleDetails>();
JSONObject jObject = null;
try {
Log.d(WebServiceHelper.TAG, "WebserviceHelperOnLogin>>>>>>>>>>>");
vdetails = new VehicleDetails();
METHOD_NAME = "getPushNotifyStatus";
Log.d(WebServiceHelper.TAG, "URL>>>>>>>>" + URL + METHOD_NAME);
HttpPost request = new HttpPost(URL + METHOD_NAME);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("clientCode", clientCode));
postParameters.add(new BasicNameValuePair("secretCode", secretode));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
postParameters);
request.setEntity(entity);
HttpResponse response = getThreadSafeClient().execute(request);
entityResponse = response.getEntity();
result = EntityUtils.toString(entityResponse, HTTP.UTF_8);
// Log.i("FB", "result ::: " + result);
Log.d(TAG, "ResultPushStatus>>>>" + result);
jObject = new JSONObject(result);
vdetails.status_login = jObject.getString("message");
// Log.i("FB", "contact.status_login ::: " + contact.status_login);
if (vdetails.status_login.contentEquals("success")) {
jObject = new JSONObject(jObject.getString("data"));
vdetails.pushStatus = jObject.getString("push_status");
Log.d(TAG, "Push Status==================>" + vdetails.pushStatus);
} else if (vdetails.status_login.contentEquals("failed")) {
String Reason = jObject.getString("data").toString();
Log.d(WebServiceHelper.TAG, "Fail Reason>>>>>" + Reason);
vdetails.failReason = Reason;
}
} catch (Exception e) {
e.printStackTrace();
}
return vdetails;
}
public static VehicleDetails[] getAllVehicles(String clientCode, String
secretCode) throws ClientProtocolException, IOException, JSONException {
VehicleDetails[] vd = null;
String result = null;
VehicleDetails vdetails = null;
ArrayList<VehicleDetails> vehicleArrayList = new ArrayList<VehicleDetails>();
JSONObject jObject = null;
String loginUrl = "getAllVehicles";
try {
HttpPost request = new HttpPost(URL + loginUrl);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("clientCode", clientCode));
postParameters.add(new BasicNameValuePair("secretCode", secretCode));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
request.setEntity(entity);
HttpResponse response = getThreadSafeClient().execute(request);
entityResponse = response.getEntity();
result = EntityUtils.toString(entityResponse, HTTP.UTF_8);
Log.d(TAG, "result>>" + result);
JSONObject object = (JSONObject) new JSONTokener(result).nextValue();
VehicleDetails.status_login = object.getString("message");
if (VehicleDetails.status_login.contentEquals("success")) {
JSONArray array = object.getJSONArray("data");
vehicleArrayList.clear();
for (int i = 0; i < array.length(); i++) {
Log.d(TAG, "LiveTracking>>>>>>>>>>>");
JSONObject jObj = array.getJSONObject(i);
String vehicleId = jObj.getString("vehicle_id").toString();
String vehicleNumber = jObj.getString("vehicle_number").toString();
vdetails = new VehicleDetails();
vdetails.vehicleId = vehicleId;
vdetails.vehicleNo = vehicleNumber;
vehicleArrayList.add(vdetails);
}
vd = new VehicleDetails[vehicleArrayList.size()];
for (int x = 0; x < vehicleArrayList.size(); ++x) {
vd[x] = (VehicleDetails) vehicleArrayList.get(x);
}
} else if (VehicleDetails.status_ login.contentEquals("failed")){
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jObj = array.getJSONObject(i);
vdetails.failReason = jObj.getString("data").toString();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return vd;
}
This is my log show.
05-02 14:34:40.597: W/System.err(10261): org.json.JSONException: Value [{"push_status":"1"}] of type org.json.JSONArray cannot be converted to JSONObject
05-02 14:34:40.617: W/System.err(10261): at org.json.JSON.typeMismatch(JSON.java:107)
05-02 14:34:40.627: W/System.err(10261): at org.json.JSONObject.<init>(JSONObject.java:158)
05-02 14:34:40.627: W/System.err(10261): at org.json.JSONObject.<init>(JSONObject.java:171)
Whats the reason for this?please Help me
Response is not a JSON object ,it's a JSON array with one element.
JSONArray a = new JSONArray("[{your JSON code}]");
JSONObject = a.getJSONObject(1);
In the following line, 'data' returns a JSON Array not a String. (Since it is enclosed in [])
jObject = new JSONObject(jObject.getString("data"));
So you'll need to get the jsonArray first.
JSONArray jArray = jObject.getJSONArray("data");
Then get the first object from the array.
JSONObject dataObject = jArray.getJSONObject(0);
now fetch the String.
String pushStatus = dataObject.getString("push_status");

send JSON to server via HTTP put request in android

How to wrap given json to string and send it to server via Http put request in android?
This is how my json look like.
{
"version": "1.0.0",
"datastreams": [
{
"id": "example",
"current_value": "333"
},
{
"id": "key",
"current_value": "value"
},
{
"id": "datastream",
"current_value": "1337"
}
]
}
above is my json array.
below is how I wrote the code but, its not working
protected String doInBackground(Void... params) {
String text = null;
try {
JSONObject child1 = new JSONObject();
try{
child1.put("id", "LED");
child1.put("current_value", "0");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(child1);
JSONObject datastreams = new JSONObject();
datastreams.put("datastreams", jsonArray);
JSONObject version = new JSONObject();
version.put("version", "1.0.0");
version.put("version", datastreams);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPut put = new HttpPut("url");
put.addHeader("X-Apikey","");
StringEntity se = new StringEntity( version.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
put.addHeader("Accept", "application/json");
put.addHeader("Content-type", "application/json");
put.setEntity(se);
try{
HttpResponse response = httpClient.execute(put, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
}
catch (Exception e) {
return e.getLocalizedMessage();
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return text;
}
please help on this
this is one sample.
JSONObject Parent = new JSONObject();
JSONArray array = new JSONArray();
for (int i = 0 ; i < datastreamList.size() ; i++)
{
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", datastreamList.get(i).GetId());
jsonObj.put("current_value", datastreamList.get(i).GetCurrentValue());
array.put(jsonObj);
}
Parent.put("datastreams", array);
Parent.put("version", version);
and for sending that:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity( Parent.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
post.setEntity(se);
client.execute(post);
EDIT
in this sample datastreamList that used in for statement is a list that you must have for all value that want send to server ( one list of one class that have 2 property , id and value ), actually i think you have two class like bellow:
class A {
List<Datastreams> datastreamList
String version;
//get
//set
}
class Datastreams {
String id;
String current_value; // or int
//get
//set
}
and in your code you must have one object of A class that want send to server, so you can use first part to map your object to json.
If you prefer to use a library then I'll prefer you to use Ion Library by Kaush.
Form this library you can simply post your JSON like this :
JsonObject json = new JsonObject();
json.addProperty("foo", "bar");
Ion.with(context, "http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
// do stuff with the result or error
}
});
Just you have to send as a String so store following JSON data in String
{
"version": "1.0.0",
"datastreams": [
{
"id": "example",
"current_value": "333"
},
{
"id": "key",
"current_value": "value"
},
{
"id": "datastream",
"current_value": "1337"
}
]
}
then you have to send like:
pairs.add(new BasicNameValuePair("data", finalJsonObject.toString()));
The '{' bracket represent a object and '[' represent an array or list. In your case create a bean
YourObj{
private String version;
private List<DataStream> datastreams;
//getters
//setters
}
DataStream{
private String id;
private String current_value;
//getters
//setters
}
use org.codehaus.jackson:jackson-xc jar for json parssing
use ObjectMapper
String to Object
YourObj obj = new ObjectMapper().readValue(stringyouwanttopass,new TypeReference<YourObj>(){});
now you can use the parsed value.
or you can set the values to the YourObj
YourObj obj =new YourObj();
obj.setVersion(1.0.0);
List<Datastream> datastreams=new ArrayList<Datastream>();
Datastream datestr=new Datastream();
datestr.setId("example");
datestr.setCurrent_value("333");
datastreams.add(datestr);
datestr.setId("key");
datestr.setCurrent_value("value");
datastreams.add(datestr);
datestr.setId("datastream");
datestr.setCurrent_value("1337");
datastreams.add(datestr);
JSONObject jsonget = new JSONObject(appObject);
jsonget.toString();
Connecting server using Jersey
Client client = Client.create();
WebResource webResource = client.resource("serverURl");
ClientResponse response = webResource.path("somePath")
.type("application/json").accept("application/json")
.post(ClientResponse.class, jsonget.toString());
in the server side get it as string and parse it.
here is a android Client library can help you:
Httpzoid - Android REST (JSON) Client,it has some examples and you can do put post,get request easily.
https://github.com/kodart/Httpzoid

makeHttpRequest is undefined for object

hello Guys this my code I got this error The method makeHttpRequest(String, String, List)
is undefined for the type JSONParser
how to handle this problem please someone help me out
and why makeHttpRequest is undefined for JSONParser
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Use this code:
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://10.0.2.2:8080");
try{
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
json = reader.readLine();
}catch(Exception e){
Log.d("Error",e.toString());
}

How to pass multiple parameters list in json with android, syntax issue

I have to pass a json object with a method and multiple parameters
the object must have this form
{"method":"startSession","params":"["email" "testmail#test.it", "password" "1234", "stayLogged" "1", "idClient" "IPHONE"]"}
My code in android to send this object is
HttpPost httppost = new HttpPost(BASE_URI);
JSONObject json = new JSONObject();
String email="testmail#test.it";
String emailRic="email"+" "+"\""+email+"\"";
String password="1234";
String passwordRic="password"+" "+"\""+password+"\"";
String stayLogged="1";
String stayLoggedRic="stayLogged"+" "+"\""+stayLogged+"\"";
String idClient="ANDROID";
String idClientRic="idClient"+" "+"\""+idClient+"\"";
try {
List<String> accessParameters=new ArrayList<String>();
accessParameters.add(emailRic);
accessParameters.add(passwordRic);
accessParameters.add(stayLoggedRic);
accessParameters.add(idClientRic);
String par=accessParameters.toString();
json.put("method", "startSession");
json.put("params", par);
JSONArray postjson=new JSONArray();
postjson.put(json);
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
System.out.print(json);
HttpResponse response = mClient.execute(httppost);
if(response != null){
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
System.out.println("the answer is:\n"+sb);
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// text = sb.toString();
}
// tv.setText(text);
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
But this send an object with the wrong form
{"method":"startSession","params":"[\"email\" \"testmail#test.it\", \"password\" \"1234\", \"restaConnesso\" \"1\", \"idClient\" \"IPHONE\"]"}
(I have seen this in the debugger)
if I try to remove the value \" from the piece of code
String email="testmail#test.it";
String emailRic="email"+" "+"\""+email+"\"";
String password="1234";
String passwordRic="password"+" "+"\""+password+"\"";
String stayLogged="1";
String stayLoggedRic="stayLogged"+" "+"\""+stayLogged+"\"";
String idClient="ANDROID";
String idClientRic="idClient"+" "+"\""+idClient+"\"";
The object sent assume the form
{"method":"startSession","params":"[email testmail#test.it, password 1234, restaConnesso 1, idClient IPHONE]"}
how can I sent the json with exacty this sintax???
{"method":"startSession","params":"["email" "testmail#test.it", "password" "1234", "stayLogged" "1", "idClient" "IPHONE"]"}
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
//Firstly declare & create a json object from the desired json as a whole.
/* How to create Json*/
JSONObject jObjectData = new JSONObject();
// Create Json Object using Facebook Data
jObjectData.put("method", "startSession");
ArrayList<String> list = new ArrayList<String>();
list.add("email");
list.add("testmail#test.it");
etc... ....
JSONArray jsArray = new JSONArray(list);
jObjectData.put("params", jsArray);
StringEntity stringEntity = new StringEntity(jObjectData.toString());
httpost.setEntity(stringEntity);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
response = httpclient.execute(httpost, responseHandler);
/* Create Json object for set parameter*/
JSONObject jObjectData = new JSONObject();
// set your first parameter name
jObjectData.put("parameter1", "startSession");
ArrayList<JSONObject> list = new ArrayList<JSONObject>();
// for 1 parameter
JSONObject jObjectData1 = new JSONObject();
jObjectData1.put("email","testmail#test.it");
jObjectData1.put("password","1234");
jObjectData1.put("stayLogged","1");
jObjectData1.put("idClient","IPHONE");
list.add(jObjectData1);
JSONArray jsArray = new JSONArray(list);
// set your second parameter has more value
jObjectData.put("parameter2", jsArray);
jObjectData string is look like below string:-
{"parameter1":"startSession",
"parameter2": [{ "email": "testmail#test.it",
"password": "1234",
"stayLogged": "1",
"idClient": "IPHONE"
}]
}
I'm not sure but, isn't the problem the fact that you are trying to send an array but are instead sending a string?
Original:
{"method":"startSession",
"params":"["email" "testmail#test.it", "password" "1234", "stayLogged" "1", "idClient" "IPHONE"]"}
Should be something like this instead (no quotes around the array):
{"method":"startSession",
"params": ["email" "testmail#test.it", "password" "1234", "stayLogged" "1", "idClient" "IPHONE"]}
Edit: Actually I think you actually want a nested object:
{"method":"startSession",
"params": { "email": "testmail#test.it",
"password": "1234",
"stayLogged": "1",
"idClient": "IPHONE"
}
}
No?
Edit #2: You should take a look at how to properly use JSONArray and JSONObject, this page has some good examples.

Categories

Resources