Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send JSON data as Body using Retrofit android

I am trying to post below JSON array on server.

{
    "order": [{
            "orderid": "39",
            "dishid": "54",
            "quantity": "4",
            "userid":"2"
        },{
            "orderid": "39",
            "dishid": "54",
            "quantity": "4",
            "userid":"2"
        }]

}

I am using this below :

private void updateOreder() {

    M.showLoadingDialog(GetDishies.this);
    UpdateAPI mCommentsAPI = APIService.createService(UpdateAPI.class);

    mCommentsAPI.updateorder(jsonObject, new Callback<String>() {
        @Override
        public void success(String s, Response response) {
            M.hideLoadingDialog();
            Log.e("ssss",s.toString());
            Log.e("ssss", response.getReason());
        }

        @Override
        public void failure(RetrofitError error) {
            M.hideLoadingDialog();
            Log.e("error",error.toString());
        }

    });

}

I am getting below error:

 retrofit.RetrofitError: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 2 column 6 path $

updateApi Code:

@POST("updateorder.php")
    void updateorder(@Body JSONObject object,Callback<String>());

Can any one please tell me my mistake?

Thanks in advance

like image 952
Mayuri Ruparel Avatar asked Sep 25 '15 05:09

Mayuri Ruparel


3 Answers

Create OrderRequest Class

public class OrderRequest {

@SerializedName("order")
public List<Order> orders;
}

create Order Class

    public class Order {

    @SerializedName("orderid")
    public String Id;
}

EndPoint

public interface ApiEndpoint{
  @POST("order")
  Call<String> createOrder(@Body OrderRequest order, @HeaderMap HashMap<String,String> headerMap);
}

Use this type of implementation in the mainActivity which call to service

HashMap hashMap= new HashMap();
    hashMap.put("Content-Type","application/json;charset=UTF-8");

OrderRequest orderRequest = new OrderRequest();
List<Orders> orderList = new ArrayList();

Orders order = new Order();
order.Id = "20";
orderList.add(order);
//you can add many objects

orderRequest.orders = orderList;

Call<String> dataResponse= apiEndPoint.createOrder(orderRequest,hashMap)
dataResponse.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            try{

            }catch (Exception e){

            }
        }   

In the createOrder method we donot need to convert object into Json. Because when we build retrofit we add converter factory as a GsonConverterFactory. It will automatic convert that object to the JSON

 retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
like image 76
Ishan Fernando Avatar answered Sep 23 '22 02:09

Ishan Fernando


try to modify your code to Retrofit 2

compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'

Your service :

@POST("updateorder.php")
Call<String> updateorder(@Body JsonObject object);

Call retrofit

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(RetrofitService.baseUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

Pass your Json using GSON :

JsonObject postParam = new JsonObject
postParam.addProperty("order",yourArray) ;

Finally :

Call<String> call = retrofitService.updateorder(postParam);


    call.enqueue(new Callback<String>() {
         @Override
         public void onResponse(Call<String>callback,Response<String>response) {
            String res = response.body();
         }
            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
    });

I hope to be helpful for you .

like image 21
Abbes Yassine Avatar answered Sep 20 '22 02:09

Abbes Yassine


If you want to post a JSON request using Retrofit then there are two methods to follow.

1. Option one - Seraialized Object
Create a serializable object(In simple terms convert your JSON object into a class) and post it using Retrofit.
If you don't know how to do it use this URL to 

convert your JSon object to a class jsonschema2pojo

Example : Lets say in your case JSon object class name is Order. 

Then inside the class you have to define your variables that matches to JSon structure.(Inner block define by [] is an array of objects). And you have to define getters and setters(I didn't include them here to save spacing)

public class Order implements Serializable{
private List<Order> order = null; //Include getters and setters
}

2. Option Two - Raw json (I prefer this one)
Create a JsonObject object and pass it (Remember not a JSONObject. Though both appears to be the same there is a distinct difference between them. Use exact same characters)

JsonObject bodyParameters = new JsonObject();
JsonArray details= new JsonArray();
JsonObject orderData= new JsonObject();
orderData.addProperty("orderid", "39");//You can parameterize these values by passing them
orderData.addProperty("dishid", "54");
orderData.addProperty("quantity", "4");
orderData.addProperty("userid", "2");
details.add(orderData)
bodyParameters.add("order", details);

Create Retrofit instance
retrofit = new Retrofit.Builder()
                    .baseUrl(baseURL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(okHttpClient)
                    .build();

Retrofit Service(You have to create a service class and define instance)
@POST("<Your end point>")
Call<ResponseObject> updateOrder(@Body JsonObject bodyParameters);

Request Call
Call<ResponseObject> call = postsService.updateOrder(bodyParameters);
//postsService is the instance name of your Retrofit Service class
like image 30
Neyomal Avatar answered Sep 21 '22 02:09

Neyomal