How pass values into web service using JSON - android

I am new in android.Currently i am working in web service.But this time i got one problem.I want to pass values into server using json.The JSOn array is in this form.
{"request":{"api_key":"valid api key", "action":"register", "firstName":"aromal", "lastName":"chekavar", "email":"aromal#mstcochin.com", "address":"test address", "city":"test city", "state":"test state", "dob":"2008-06-26", "gender":"Male", "zipCode":"123456", "pin":"1234", "deviceId":"valid device id", "gcmRegId":"111111","country":"5"
}}
Please help me..

JSONObject request = new JSONObject();
JSONObject jobj = new JSONObject();
jobj.put("api_key", valiapikey);
jobj.put("action", register);
...............................
request.put("request", jobj);
Create a JSON object(jobj here) enclosing all your parameters with their keys and then enclose it in "request" JSON object.

Related

How to get string and hashmap mixed value inside a hashmap

I'm using volley and trying to make request to API that I'm working on. Json Request should be like this format.
{
"name": "API name",
"param":{
"email": "user#mail.com",
"password": "password"
}
}
I've tried to use hashmap but I don't know how to put
<string string>
<string, hashmap>
this is getting complicated.
Now, how should I put these values in hashmap and convert it to JSONObject and send request to server.
If this is not the way it should be done, then what should I use instead?
HahMap can not be used for JSON serialization, I suggest you to use org.json (https://mvnrepository.com/artifact/org.json/json)
Ex:
JSONObject jsonObj = new JSONObject();
JSONObject param = new JSONObject();
param.put("email","blhablah");
param.put("password","blhablah");
jsonObj.put("name", "apiName");
jsonObj.put("param", param);
System.out.println(jsonObj.toString());
This will give you the json, like follwoing :
{"param":{"password":"blhablah","email":"blhablah"},"name":"apiName"}

JSON Array with RequestParams in Android Asynchronous Http Client

I have trouble to send a JSON POST Request to my server.
My server accept a POST with application/json as type and an example would be like this:
{
"name": "Group4",
"users": [
{"email": "user#example.org"},
{"email": "user2#example.org"},
]
}
If I send this by a REST client I get 200 OK as response, everything fine.
My Android client uses the Android Async HTTP Library (http://loopj.com/android-async-http/) and a documentation to the RequestParams class is here https://loopj.com/android-async-http/doc/com/loopj/android/http/RequestParams.html
RequestParams params = new RequestParams();
String userName = getUserName();
List<String> userList = getUserList();
params.put("name", userName);
JSONArray users = new JSONArray();
for(String user : userList) {
JSONObject obj = new JSONObject();
try {
obj.put("email", user);
} catch (JSONException e) {
// ...
}
users.put(obj);
}
params.put("users", users);
I thought this will create exactly a JSON like my example. I don't know if I have the possibility to get a JSON string of this RequestParams. I only can access the parameter as a String:
name=Test&users=[{"email":"user#example.org"}, {"email":"user2#example.org"}]
My server don't even accept the request and fails directly with the error:
AttributeError: 'unicode' object has no attribute 'iteritems'
The problem has to be at the point where I create the RequestParams. Can someone tell me what is wrong with that? I thought I have to create an array with name "users" and then add objects in it with key-value items.
Just put List<> to your RequestParams. Here is the example:
RequestParams params = new RequestParams();
List<String> list = new ArrayList<String>(); // Ordered collection
list.add("Java");
list.add("C");
params.put("languages", list);
//above code will generate url params: "languages[0]=Java&languages[1]=C"
So you don't need to add it manually using Loop sequence.
See the docs here
Will recommend to use Volley for Async calls in Android https://developer.android.com/training/volley/index.html

How to send an Object as JSON to a Server using NameValuePairs?

I am attempting to add some Book(title, author, year) into my book table in a server using an AsyncTask, but i am getting missing bookobject as JSONfrom the method addBook(from the server). So i made a bookObject like this:
JSONObject jObj = new JSONObject();
jObj.put("title", "JAVA");
jObj.put("author", "me");
jObj.put("year", 2005);
After that, i wanna use(my intention is to send this book Object):
List<NameValuePair> nameValuePairs = new ArrayList<>(1);
nameValuePairs.add(new BasicNameValuePair(jObj)); //Error
new AaaBookAsyncTask(this).execute(new Pair<>(nameValuePairs, httpClient));
The problem is BasicNameValuePaircannot applied to JSONObject, but now how can i send the book Object? - Any help or hints is very appreciated.Thanks, Carl
You could send the JSON as a string and then decode it on your server before storing it in your database.

android: json response is just a String

I know how to access to json. Now I get a json response like that:
"2014-02-16T20:27:54+00:00"
https://openligadb-json.heroku.com/api/last_change_date_by_league_saison?league_shortcut=bl1&league_saison=2013
this is not a JSONArray and has no Name. How can I access it?
It is not json formatted data. If you need it in json, you can generate it by yourself like this :
JSONObject json = new JSONObject();
json.put("data", "2014-02-16T20:27:54+00:00" );
json.toString(); // { "data" : ""2014-02-16T20:27:54+00:00" } it is json
In other case you can work with this data as typical String. It depends on what you need to achieve.
Good luck!

Android client error with returning valid JSON from Django server

I am hoping someone might be able to help me out.
I have a Django server that is returning JSON to an iOS application. On the Django server, we are using
return HttpResponse(json.dumps(session_dict),mime_type)
to return the JSON to the client as (via Wireshark)
2f
{"session": "bcb493fb21ae8fcd9152e1924b3e5d9a"}
0
This response is somehow valid to the iOS application able to be parsed by the iOS JSON client libraries. This does not look like valid Json to me so I am surprised it works.
However, if I use the following in Android, I get an error:
Value session of type java.lang.String cannot be converted to JSONObject.
jsonObjSend.put("username", strUserName);
jsonObjSend.put("password", strPassword);
Add a nested JSONObject (e.g. for header information)
JSONObject header = new JSONObject();
header.put("deviceType","Android"); // Device type
header.put("deviceVersion","2.0"); // Device OS version
header.put("language", "es-es");
jsonObjSend.put("header", header);
// Output the JSON object we're sending to Logcat:
Log.i(TAG, jsonObjSend.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
try {
// Send the HttpPostRequest and receive a JSONObject in return
JSONObject jsonObjRecv = HttpClient.SendHttpPost(URL, jsonObjSend);
String sessionId = jsonObjRecv.getString("session");
Any suggestions?
Thank you,
Greg
Does your HttpClient.sendHttpPost method return a JSONObject? Not sure if it parses the response body from the HTTP POST into a JSONObject automatically. If it doesn't, then you would have to do that using the JSONTokener or use a library like Gson.
google's GSON may be a better choice you can convert an instance to json string directly such as
User user =new User("tom","12");
Gson gson =new Gson();
json=gson.toJson(user);

Categories

Resources