android - 如何在 Retrofit2 api 调用中调用 JSONObject?
问题描述
示例:我的输入是
{
"company_id": 1,
"customer_id": 1,
"items": [
{
"service_id": "1",
"service_description": "description here",
"service_quantity": 1,
"service_uom": "number",
"service_price": "10000",
"service_total": "10000",
"service_taxid": 1,
"service_taxvalue": "10"
},
{
"service_id": "2",
"service_description": "description here",
"service_quantity": 1,
"service_uom": "number",
"service_price": "10000",
"service_total": "10000",
"service_taxid": 1,
"service_taxvalue": "10"
}
]
}
我声明如下:API Call-
@FormUrlEncoded
@POST("URL")
Observable <SampleResponse> generateInvoice(@Field("company_id") Integer companyId, @Field("customer_id") Integer customer_id, @Field("items") JSONArray params);
宣言:
JSONObject service1 = new JSONObject();
try {
service1.put("service_id", id);
service1.put("service_description", Desc);
service1.put("service_quantity", Integer.valueOf(Qty));
service1.put("service_uom", "number");
service1.put("service_price", Amt);
service1.put("service_total", GAmt);
service1.put("service_taxid", 1);
service1.put("service_taxvalue", 5);
Log.d("jsonobject created", "" + service1);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray array = new JSONArray().put(service1);
presenter.generateInvoice(1,"company123",array);
后端错误:'{\"service_id\":3,\"service_description\":\"Mobile Application\",\"service_quantity\":5,\"service_uom\":\"number\",\"service_price \":\"650\",\"service_total\":\"3640\",\"service_taxid\":1,\"service_taxvalue\":5}';
斜线不在 api 输入调用中,而是在后端看到。这会导致 http 500 错误。我尝试添加@Body RequestClass 并删除@FormUrlEncoded,但这不起作用,因为它有@Field。或者我们是否需要 2 个 api 调用来实现这一点?
解决方案
已解决的问题 对于给定的输入,我们应该创建一个 json 对象并使用 @Body RequestBody 发布数据。无需@Field。下面是用于制作一个包含所有数据的单个 json 对象的代码-
JSONArray itemsArray = new JSONArray();
JSONObject service1 = new JSONObject();
JSONObject finalobject = new JSONObject();
try {
service1.put("service_id", id);
service1.put("service_description", Desc);
service1.put("service_quantity", Integer.valueOf(Qty));
service1.put("service_uom", "number");
service1.put("service_price", Amt);
service1.put("service_total", GAmt);
service1.put("service_taxid", 1);
service1.put("service_taxvalue", 5);
finalobject.put("company_id",companyid);
finalobject.put("customer_id",CUST_ID);
itemsArray.put(service1);
finalobject.put("items",itemsArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finalobject 将给出 json 对象
推荐阅读
- opengl - 使用 glReadpixels 编辑 Uv 贴图以创建法线贴图
- php - 如何使用 PHP 在同一数组层次结构级别中获取具有关键字 ID 的值
- javascript - Bootstrap Datepicker:允许多种格式
- python - Pygame不让我改变图像的颜色
- c# - Azure DB 上 C# 中的 SQL 插入语句 - 运行速度非常慢
- css - 如何在任何切换条件下使这个主容器响应侧边栏
- python - 如何比较 2 个对象检测列表
- sql - 如何在 Redshift 中找到无法转换为日期的值?
- r - R/Shiny:带有长度为零的参数的 If 语句
- php - 有旧的 php web 如何将 mssql 更改为 sqlsrv all