retrofit2 发送json数据_如何使用Retrofit android将JSON数据作为Body发送

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值