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() {
@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());
Can any one please tell me my mistake?
Thanks in advance
解决方案
Create OrderRequest Class
public class OrderRequest {
@SerializedName("order")
public List orders;
}
create Order Class
public class Order {
@SerializedName("orderid")
public String Id;
}
EndPoint
public interface ApiEndpoint{
@POST("order")
Call createOrder(@Body OrderRequest order, @HeaderMap HashMap 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 orderList = new ArrayList();
Orders order = new Order();
order.Id = "20";
orderList.add(order);
//you can add many objects
orderRequest.orders = orderList;
Call dataResponse= apiEndPoint.createOrder(orderRequest,hashMap)
dataResponse.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response 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();