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.
Related
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
Good day.Im sending post request to php server side like this
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("my server name");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
/*StringTokenizer tokens = new StringTokenizer(from.getText().toString(), "-");
String shortstring = tokens.nextToken();
String longstring = tokens.nextToken();
StringTokenizer tokens2 = new StringTokenizer(to.getText().toString(), "-");
String shortstringto = tokens2.nextToken();
String longstringto = tokens2.nextToken();*/
try {
reqEntity.addPart("type", new StringBody("3"));
Server side receives it like this
Array
(
[type] => 3
)
All seems good which afar he wants me to send to him an array.I do send it like this
ArrayList<String> array = new ArrayList();
aray.add("hello");
reqEntity.addPart("array", new StringBody(array.toString()));
he receives it like this
Array
(
[type] => 1
[array]=> [hello];
)
All seems good but he assumes thats I'm sending wrong and he wants the array to be send so he can receive it like this way.
Array
(
[type] => 1
[array]=> Array(
[header name of my array]=>"value of array"
)
)
I google every bit i read every single line of every site,and did not found anything even close to what he wants as if i send array it will be like i wrote,otherwise he just wants array of inside another array with KEY name of inner array and with VALUE of inner array,which i don't know but somehow not possible for my opinion in the way he wants.So is it possible?can i send array the way he wants in my last written code?
Sorry don't have enough points to post a comment. But you need to provide a little more information about which server you are using.
If you are using PHP, it is pretty much simple, once you have set up a secure connection you just need to send the response in the following manner:
$response["success"] = 0;
$response["message"] = "Some Message";
die(json_encode($response));
JSONObject jsonObject =new JSONObject();
JSONArray taskDoneJsonArray= new JSONArray();
taskDoneJsonArray.add("aa");
JSONArray nextStepsJsonArray= new JSONArray();
nextStepsJsonArray.add("bb");
try {
jsonObject.put("accessToken", "something");
jsonObject.put("taskDone",taskDoneJsonArray);
jsonObject.put("nextTask",nextStepsJsonArray);
jsonObject.put("issueRemaining",issuesQueriesJsonArray);
}
catch (JSONException jsonException){
ToastMessage.show(context,context.getResources().getString(
R.string.error)+jsonException.getMessage());
}
Now use jsonObject
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.
Hi all I have a List where I add parameters, whcih I use to connect and do operations in a MySQL with the help of PHP script. The PHP script expects a "id", which is a int that retrieves from Android app. However, although I send the intent with the correct id the List NameValuePairs converts it to a especific format in this case. For example, if the id is 2 the final params will be id=2, which is a String that the PHP script does not understand. I would like to know if there is a way of removing the first characters and instead of id=2, only send 2.
Here is the code I use
public void monitorizar() throws Exception{
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
JSONObject json = jsonParser.makeHttpRequest(url_detalles, "GET", params);
Log.d("params", String.valueOf(params));
ArrayList<HashMap<String, String>> temp;
temp = new ArrayList<HashMap<String, String>>();
Obviously, when I send the params to the php script, it gives me an error because the id is not an integer and it is written with this format id="id".
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