How to send JSON object using RestClientHelper? - android

I need to implement login API in android. For that, I used RestClientHelper, a 3rd Party library in android https://github.com/ravi123shanker/SimpleRestClientHelper
But i need to send a json object to url like:
{
"id":1,
"username":"hello",
"password":"1223"
}
From thier documentation i able to put value to postParams like :
{login=[{"id":1,"password":"hello","username":"1223"}]}
But I need to send like the above format! How could I do that:
my function is:
JSONArray productsJson = new JSONArray();
try {
JSONObject eachProduct = new JSONObject();
eachProduct.put("fcmid", fcm_id);
eachProduct.put("password", pin);
eachProduct.put("username", username);
productsJson.put(eachProduct);
}
catch (Exception e){
Log.e("Exception", "error");
}
ArrayMap<String, Object> postParams=new ArrayMap<>();
postParams.put("login", productsJson.toString());
Log.e("postParams","data "+postParams.toString());
RestClientHelper.getInstance().post(Constants.BASE_URL_USER_LOGIN , postParams, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
}
#Override
public void onError(String error) {
}
});
Any Help, please??

It seems like you need to insert your JsonObject into a JsonArray and then bind it to the login parameter
JSONArray jArray = new JSONArray();
jArray.put(productsJson);
...
postParams.put("login", jArray.toString());

Related

Not able to fetch JSON data [using volley Library] in Android

The jason array request code goes like this:
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET,url, (JSONArray) null , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Log.d("Response:", String.valueOf(response.getJSONObject(0)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response not recieved", Toast.LENGTH_SHORT).show();
}
});
And I've used a singleton instance of a request queue, to fetch the data,
AppController.getInstance(context.getApplicationContext()).addToRequestQueue(arrayRequest);
I'm using an api service that supplies a bunch of questions (The api generates a url, which returns a collection of JSON Objects, An Array (Just try and Open the url link, the json array will be seen)
But when I run the app, the request is not even getting a response,the progam flow is going into the error listner block.
Can someone explain this behaviour? Is it because the JSON array supplied by the url, has nested arrays? Why?
I tried reading and anlyzing other questions here, which might have the same issue, But i found nothing.
You want to just change JsonArrayRequest to JsonObjectRequest:
Please copy and paste below code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String category = jsonObject.getString("category");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
// hide the progress dialog
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, "TAG");
Follow this link for learn other request: Androidhive

i need to post multiple json objects

I need to post multiple json objects. i want to post this data to the server. I get null value. here i attached api and function.
my json object:
{
"test_id":5,
"user_id":null,
"org_id":2,
"schedule_id":15,
"group_id":null,
"next_section_id":"",
"current_section":
{
}
}
Here I attached api and function.
funtion :
try {
JSONObject paramObject = new JSONObject();
JSONObject current_section = new JSONObject();
paramObject.put("test_id", 5);
paramObject.put("user_id", "null");
paramObject.put("org_id", 2);
paramObject.put("schedule_id", 15);
paramObject.put("group_id", "null");
paramObject.put("current_section",current_section);
Call<Test_Responce> userCall = api_interface.testRes(paramObject);
userCall.enqueue(new Callback<Test_Responce>() {
#Override
public void onResponse(Call<Test_Responce> call, Response<Test_Responce> response) {
if (response.isSuccessful()){
Toast.makeText(getApplicationContext(),"success",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"else",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Test_Responce> call, Throwable t) {
Toast.makeText(getApplicationContext(),"fail",Toast.LENGTH_SHORT).show();
}
Try using JsonObject from gson (dont use JSONObject)
JsonObject paramObject =new JsonObject();
paramObject.addProperty("test_id", 5);
paramObject.addProperty("user_id", "null");
paramObject.addProperty("org_id", 2);
paramObject.addProperty("schedule_id", 15);
paramObject.addProperty("group_id", "null");
JsonObject current_section =new JsonObject();
paramObject.add("current_section",current_section);
and change interface like this
#POST("take_tests")
Call<Test_Responce> testRes(#Body JsonObject paramObject);
You should use JSONObject.NULL instead of "null", like
paramObject.put("user_id", JSONObject.NULL);

get object integer json to android studio

json with int key value
I've been stuck, to call json like this to android studio using volley, I've never done this before
According to this json with int key value
you are
receiving jsonArray instead of jsonObject
so you have to
send the request of JsonArray with volley
then the request will return jsonArray then you can get your string like this.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest("url", new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response)
{
try
{
for (int i=0;i<response.length();i++)
{
JSONArray jsonArray = response.getJSONArray(i);
for (int j=0;j<jsonArray.length();j++)
{
String yourString = jsonArray.getString(j);
// you can convert it into int as per your requirement
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
}
});

How can I parse a JSON request using Volley?

I am using the Volley Facebook library to parse the JSON object by passing the String Parameter. But it's throwing JSON exception.
[
{
"error":false,
"newsletter":[
{
"title":"IPS Informa",
"date":"2015-12-02",
"posted_by":"admin",
"image":"1449324052220174144.png",
"description":"Hello World",
"id":"4",
"post_count":"0"
},
{
"title":"IPS Informa",
"date":"2015-11-30",
"posted_by":"admin",
"image":"1449324052220174144.png",
"description":"Hello Worl Two",
"id":"1",
"post_count":"6"
}
]
}
]
And here is My Android Code to parse my JSON request:
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hidePDialog();
try {
JSONObject first = new JSONObject(response);
String err = first.getString("error");
JSONArray second = first.getJSONArray("newsletter");
fisco_tips.clear();
// Parsing json
for (int i = 0; i < second.length(); i++) {
JSONObject obj = second.getJSONObject(i);
FisoTipsSinglton fisco_obj = new FisoTipsSinglton();
//Set Newsletter ID
fisco_obj.setFisco_id(obj.getString("id"));
//Set Title
fisco_obj.setTitle(obj.getString("title"));
//Set Posted Date
fisco_obj.setPosted_date(obj.getString("date"));
//Set Posted By
fisco_obj.setPosted_by(obj.getString("posted_by"));
//Set Image URL
fisco_obj.setThumbnailUrl(obj.getString("image"));
//Set Short Description
fisco_obj.setShort_description(obj.getString("description"));
fisco_obj.setPost_count(obj.getString("post_count"));
fisco_tips.add(fisco_obj);
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("Json Error", "Here is error: " + e.toString());
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidePDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("country", country);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, related_posts);
}
How can I read my JSON object using string request in Android Volley library?
The error message that you're getting:
type org.json.JSONArray cannot be converted to JSONObject
indicates that you're trying to convert a JSONArray to a JSONObject. This happens in the first line of code in your try block.
JSONObject first = new JSONObject(response);
You're passing the entire response to the JSONObject constructor, but the response is wrapped in [ ], so it's a JSONArray, not a JSONObject. Your first step should be to parse the response as a JSONArray, get the JSONObject from the first element of the array, then continue parsing.
try {
JSONArray wrapper = new JSONArray(response);
JSONObject first = (JSONObject)wrapper.get(0);
boolean err = first.getBoolean("error");
JSONArray newsletters = first.getJSONArray("newsletter");
// Parsing json
for (int i = 0; i < newsletters.length(); i++) {
JSONObject news = newsletters.getJSONObject(i);
.
.
.
}
} catch (JSONException e) {
Log.d("MainActivity.java", e.toString());
}
If there's a chance that your data source might return an empty array, you should do more error checking than I've shown here.
String err = first.getString("error");
Should be:
Boolean err = first.getBoolean("error");
Plus what Bill the Lizard said.
Instead of using Volley check OkHTTP with Retrofit. It will wrap responses automatically ;)

How to post json object using retrofit

i wanted to post the json object using retrofit.
i have created following interface:
public interface syncinter {
#POST("url")
void sync_data(#Body JSONObject ordObj, Callback<JsonObject> callback);
}
the following data i want it to post.
final JSONObject ordJsonObj = new JSONObject();
JSONArray ordJsonArray = new JSONArray();
try {
ordJsonObj.put("Order_Nos",mOrdArr.size());
for (int i=0; i<mOrdArr.size();i++) {
JSONObject ordObj = new JSONObject();
ordObj.put("Order_No",mOrdArr.get(i).getorderID());
ordObj.put("Order_Date",mOrdArr.get(i).getorderDate());
ordObj.put("Customer_id",mOrdArr.get(i).getCustPKID());
Customer aCust = db.getEmployee(mOrdArr.get(i).getCustPKID());
ordObj.put("Cust_name",aCust.getEmpName());// query DB
ordObj.put("Company_id",sharedpreferences.getString(OrderApplication.CompanyID,"")); // sharedP
ordObj.put("Device_Ref",mOrdArr.get(i).getOrdPKID());// sharedP
ordObj.put("User_ID",sharedpreferences.getString(OrderApplication.UserID,""));// sharedP
JSONArray prodJsonArray = new JSONArray();
ArrayList<Product> mProdArr = db.getAllProductOrder(mOrdArr.get(i).getorderID());
for (int j=0; j<mProdArr.size();j++) {
JSONObject prodObj = new JSONObject();
prodObj.put("Product_id",mProdArr.get(j).getPrID());
prodObj.put("Product_name",mProdArr.get(j).getprName());
prodObj.put("Product_Brand",mProdArr.get(j).getBrandName());
prodObj.put("Qty",mProdArr.get(j).getPrQty());
prodObj.put("Rate",(Double.parseDouble(mProdArr.get(j).getPrAmt()+"")/ mProdArr.get(j).getPrQty()));
prodObj.put("Total_Amount",(Double.parseDouble(mProdArr.get(j).getPrAmt()+"")));
prodJsonArray.put(j, prodObj);
}
ordObj.put("OrderDetails",prodJsonArray);
ordJsonArray.put(i,ordObj);
}
ordJsonObj.put("Orders",ordJsonArray);
Log.d("response", "" + ordJsonObj.toString());
I have written the following retrofit code to post the json object but with this following code I am getting
failure -> error : 400 Bad Request.
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(OrderApplication.getBase_URL)
.build();
//Creating object for our interface
syncinter api = adapter.create(syncinter.class);
api.sync_data(ordJsonObj, new Callback<JsonObject>() {
#Override
public void success(JsonObject jsonObject, retrofit.client.Response response) {
}
#Override
public void failure(RetrofitError error) {
Log.d("ERROR", String.valueOf(error));
Toast.makeText(getActivity(),"Order failed to place on Server",Toast.LENGTH_LONG).show();
}
});
i was able to post it using TypedInput declare the api as shown below
#PUT(ServerEndPoint)
void callApi(#Body TypedInput input, Callback<Response> response);
and send the json object like this
TypedInput input = null;
try {
JSONObject obj = new JSONObject();
obj.put("KEY", "value");
input = new TypedByteArray("application/json", obj.toString().getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
callApi(input, new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
}
#Override
public void failure(RetrofitError error) {
}
});
not of relative importance i am using retrofit 1.9

Categories

Resources