How to send JSON object over request to web service in android - android

I would like to pass JSON object as request to web service like i mentioned below.
Result:{
"email":"xxxxxxx",
"password":"xxxxxx",
"Marks":[
{
"mark1":"50",
"mark2":"70"
}
],
"firstname":"xxxx",
"lastname":"xxxxx"
}
My code:
...
HttpPost httppost = new HttpPost("My Url");
httppost.setEntity(new StringEntity(**message**.toString(), "UTF-8"));
Here message should have json object in above format.How could i format JSON object?
Thanks.

If you arer having trouble in implementing above json object at android side then you can construct it like below,
JSONObject message = new JSONObject();
JSONObject mParams = new JSONObject();
mParams.put("email", "xxxx");
mParams.put("password", "xxx");
JSONArray markArray = new JSONArray();
JSONObject markObj = new JSONObject();
markObj.put("mark1", "50");
markObj.put("mark2", "70");
markArray.put(markObj);
mParams.put("Marks", markArray);
mParams.put("FirstName", "xxxx");
mParams.put("lastname", "xxxx");
message.put("Result",mParams);
Now in your code
HttpPost httppost = new HttpPost("My Url");
httppost.setEntity(new StringEntity(**message**.toString(), "UTF-8"));

You can just send it like a String:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", message.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
and
$data = json_decode($json);

First of all, the JSON which you have mentioned above is INVALID.
Now,
Here message should have json object in above format.How could i
format JSON object?
=> There are 2 ways to do that:
1) Create a request structure by using JSONObject or JSONArray classes, something like:
JSONObject objRequest = new JSONObject();
objRequest.putString("email","xxxx");
objRequest.putString("password","xxxx");
while setting entity inside HttpPost object, convert it into the String value.
2) Bad way, simple generate a string value with escape sequences, something like:
String strRequest = "{\"email\":\"xxxxxxx\",\"password\":\"xxxxxx\"}";

This may help you..Use GSON library. GSON is a Google library to parse JSON resources. With regards to the Marshalling, it basically means a way to translate data structures (like objects in an OOP language) to JSON... for instance:
// Java object
class Book {
private String title;
private String isbn;
private Set<author> authors;
}
#Entity
class Author {
private String firstName;
private String lastName;
}
To...
{title: "Vocation Createurs",
isbn: "2829302680",
authors: [{firstName: "Barbara", lastName: "Polla"},
{firstName: "Pascal", lastName: "Perez"}]}

You can also use existing libraries like android-json-rpc

Related

How can i get data from server?

after running the url i am getting data in the following form
[
{
"user_name": "riz",
"gems_available": "10",
"free_gems": "110"
},
{
"match_name": "ausvsind",
"Match_start_time": "2016-03-27 19:00:56",
"season_name": "Mid-Season"
}
]
now i want to get user_name and all the data but unable to do..i am getting this data in the result after running my app but unable to fetch.below i have my java code.please help me where i am wrong.
JSONObject jsonObj = new JSONObject();
jsonObj.put("user_id", "abc#hotmail.com");
jsonArray = new JSONArray();
jsonArray.put(jsonObj);
final HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(USER_URL);
String str = jsonArray.toString().replace("[", "");
String str1 = str.replace("]", "");
httppost.setEntity(new StringEntity(str1.toString()));
resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
result = EntityUtils.toString(ent);
jsonArray1.put(result);
jsobj = new JSONObject(result);
us1 = jsobj.getString(TAG_USER_NAME);
us2 = jsobj.getString(TAG_GEMS_AVAILABLE);
us3 = jsobj.getString(TAG_GEMS_FREE);
Have a look at Retrofit : it helps you parse JSON into a java POJO automagically and will help you avoid non-differential boilerplate
https://github.com/square/retrofit
When I have to get data from a Json, I always you serialization.
Have a Look at GSON. With it, you have to create model Objects that match the json architecture. After it, you can access all your json attributes easily.
There is another, better way to do this.
Use modern libraries for API calls like Retrofit 2.0 with GSON.
Add Retrofit 2.0 to your project
Read: https://github.com/square/retrofit
Create POJO Object from your JSON
http://www.jsonschema2pojo.org/
select Source type > JSON
select Annotation style > GSON
Create API service interface
Step by step: http://square.github.io/retrofit/
Why are you removing the "[" and "]" characters? Those are part of the JSONArray? If you did not want them there, use a JSONObject instead.
I did not test this, so it will have some issues. Conceptually this should work for you:
JSONObject jsonObj = new JSONObject();
jsonObj.put("user_id", "abc#hotmail.com");
final HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(USER_URL);
httppost.setEntity(new StringEntity(jsonObj.toString()));
resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
result = EntityUtils.toString(ent);
JSONArray jsonArr = new JSONArray(result);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jobj = jsonArr.getJSONObject(i);
if (jobj.has("user_name"))
{
us1 = jobj.getString("user_name");
}
if (jobj.has("gems_available"))
{
us2 = jobj.getString("gems_available");
}
if (jobj.has("free_gems"))
{
us3 = jobj.getString("free_gems");
}
}

How receive JSON object via HttpClient?

I use HttpClient in android to send post request:
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(hostNameCollection);
StringEntity se = new StringEntity(jsonObj.toString());
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
request.setEntity(se);
HttpResponse response = client.execute(request);
Log.v("HttpLogClient.logJSONObject", "wyslano JSON");
and I'dont know how I can receive JSON object on my Java EE servlet.
you need to read the response body text, then parse as JSON,
String result = EntityUtils.toString(response.getEntity());
JSONObject jo = new JSONObject(result);
read the body of the http post ( server-side ) by getting the a stream object on the body and then reading it.
Once youve read it , convert the bytes to chars and that will be json which you can use to build a json object like a jsonNode using 'jackson' libs.
If you are using plain servlets the json stream is located in the body of the HttpServletRequest : request.getReader() or request.getInputStream();
To make things easier you could use a library handling databinding for you.
Have a look at Genson http://code.google.com/p/genson/.
YouClass object = new Genson().deserialize(request.getReader(), YourClass.class);
// or to a plain map
Map<String, Object> map = genson.deserialize(request.getReader(), Map.class);

Android POST JSON Array to Server

I am having problems trying to POST a JSON Array.
For my Android code, I pass the JSON Array into the server by doing:
interests = // JSONArray of JSONObjects
final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(PARAM_USERNAME, username));
params.add(new BasicNameValuePair(PARAM_INTERESTS, interests.toString()));
HttpEntity entity = new UrlEncodedFormEntity(params);
final HttpPost post = new HttpPost(UPDATE_INTERESTS_URI);
post.setEntity(entity);
// POST data to server
But when I read it from the server using:
$interests = $_POST["interests"];
echo $interets
It looks like [{\"a\":\"1\"},{\"b\":\"2\"}] instead of [{"a":"1"},{"b":"2"}]. The first one won't decode properly, and the second one works.
So why is it not working?
EDIT:
When I look at on Android before it posts, the JSONArray.toString() looks like [{"a":"1"},{"b":"2"}]
Don't know about android, but that looks like the magic quotes-feature of PHP is adding those slashes, if that's the case you could use this on server-side:
$interests = $_POST["interests"];
if (get_magic_quotes_gpc()) {
$interests = stripslashes($interests);
}
echo $interests;
do it in this way:
JSONObject paramInput = new JSONObject();
paramInput.put(PARAM_USERNAME, username);
paramInput.put(INTERESTS, interests.toString());
StringEntity entity = new StringEntity(paramInput.toString(), HTTP.UTF_8);
You can try to use:
StringEntity params = new StringEntity("your_Data");
instead of your UrlEncodedEntity.

passing an array of string using json

JSONObject jsonObj = new JSONObject();
jsonObj.put("email", email);
jsonObj.put("password", password);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost("http://api.readfa.st/session");
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);`
Currently I am working in an android project where i need to pass an array user[email], user[password] to a web page using json...please if any one can help me width this asap..Thank you!
I'm not sure what you mean. But I guess you need something like this:
JSONArray jsonArray = new JSONArray(listOfUsers);
String jsonRepresentationForListOfUsers = jsonArray.toString();
You can look here for further documentation.
http://developer.android.com/reference/org/json/JSONArray.html

How to use JSON for inserting records into SQL database

Let's say I store a list of names , for eg: "abc","bcd","gdf"... in an array of Strings. I have an Android app that displays each of those values along with a checkbox. I need to convert my String array into a JSON String so that I can store it in a remote database. Right now I am working on localhost with a database created using SQL Server. I need to insert the JSON string values in the database using a web service , preferably SOAP
How should I do this ? Is there any other better way to do so ?
Here is my Android code.
Thanks
In my case this works fine,
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", value1);
jsonObject.put("key2", value2);
JSONArray jArrayParam = new JSONArray();
jArrayParam.put(jsonObject);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("bulkdata",
jArrayParam.toString()));
Log.e("bulkdata", jArrayParam.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("yor remote database url");
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// get response entity
HttpEntity entity = response.getEntity();
Try it. Thnx.
Well, I just tried to show you how to write the String array to JSONObject and JSONArray.
String arr[] = {"1","parth","present","30-82011","Mumbai"};
try {
JSONObject obj=new JSONObject();
obj.put("rollno",new Integer(arr[0]));
obj.put("status",arr[1]);
obj.put("date",arr[2]);
obj.put("place",arr[3]);
System.out.print(obj.toString(1));
JSONArray list = new JSONArray();
list.put(arr[0]);
list.put(arr[1]);
list.put(arr[2]);
list.put(arr[3]);
System.out.print(list.toString(1));
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}
var arr:String = com.adobe.serialization.json.JSON.encode(Obj);
var data_projects:Array = stmt.getResult().data;
var b_data:String = com.adobe.serialization.json.JSON.encode(data_projects);
var arr:String = com.adobe.serialization.json.JSON.encode(data_projects);
var arr1:Object = com.adobe.serialization.json.JSON.decode(b_data) as Array;
 for(var d:int=0;d<=data_projects.length-1;d++)
 
{
//Mapping properties of Proxy classes with actual fields
var bbb:Object = new Object;
data.MdId = arr1[d].MD_ID;
data.MdDevId=arr1[d].MD_DEVICE_ID;
data.MdRecId=arr1[d].MD_REC_ID;
data.MdPrjId= arr1[d].MD_PRJ_ID ;
data.MdMbcId = arr1[d].MD_MBC_ID;
data.MdMbcValue= arr1[d].MD_MBC_VALUE;
data.MdParentRecId= arr1[d].MD_MBC_ID;
//below is the create method on the WSDL
ws.Create(data);
}

Categories

Resources