i need to post multiple json objects - android

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);

Related

How to send JSON object using RestClientHelper?

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());

how to get a json property by index

in a json file i have several properties, some of them contains one object and some of them are array of objects. the property that contains array of objects is called "products".
but i know the position of that property the i want to parse it is number 3. so to parse the contents of the property that is called "products"
code:
private void fetchPosts2() {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, API_BASE_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, String.valueOf(response));
String json = null;
JSONObject jresponse = null;
try {
jresponse = response.getJSONObject(3); //the arguments 3 is marked with red it is expected to be a string???
} catch (JSONException e) {
e.printStackTrace();
}
Log.i(TAG, "" + jresponse);//always null
/*String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject);
else if (json instanceof JSONArray)*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
}
You should use JsonArrayRequest instead of JsonObjectRequest to get element with index.

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 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

Android volley : how to check json type before parsing it

Is it possible to check the type of json beforehand? I'm somteimes getting an array and sometimes an object and I don't see how to handle these 2 cases without doing 2 different functions...
public void RequestApi( String url, final ApiResponse<ApiResult> completion )
{
Log.v("Performing request: ", url);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, hostname+url, (JSONObject) null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.v("RequestApi Response", response.toString());
//Log.v("Data: ", response.toString());
try {
ApiResult res = new ApiResult();
Boolean success = response.getBoolean("success");
//here need to check type, sometimes array, sometimes object
JSONArray data = response.getJSONArray("data");
res.success = success;
res.data = data;
completion.onCompletion(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ApiResult res = new ApiResult();
res.success = false;
completion.onCompletion(res);
}
}
);
AppController.getInstance().addToRequestQueue(jsonRequest);
}
Use StringRequest
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Object json = new JSONTokener(response).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO something
}
});
Most simple solution - look at first string character. If it is { - object, if [ - array. But I think better to do following:
try {
JSONObject object = new JSONObject(value);
}
catch (JSONException) {
//if it throws, "value" contains not a JSONObject
JSONArray array = new JSONArray(value);
}
After going through the API I found a simple solution.
Since you are not sure of the return type, follow mentioned below steps.
First:
JSONArray arrayInstance = new JSONArray();// declare array instance to handle both the cases
Object objectInstance = rootObject.get(key); //key is the response string holding the value either jsonArray or jsonObject
Second:
if(objectInstance instanceof JSONArray){
arrayInstance = rootObject.getJSONArray(key);
}
else{
JSONObject tempObject = rootObject.getJSONObject(key);
arrayInstance.put(tempObject);
}
Third:
You can iterate though the array for the desired processing.

Categories

Resources