Retrofit2我将如何使用具有内部json的地图json主体进行POST。让我举个例子:
{
"id_invoice": 1234,
"action": "viewed",
"data": {
"id_object": 88,
"id_store": 43,
"type": "payment"
}
}
注意“data”JSON对象如何具有内部JSON。如何将所有这些放入地图中,我可以使用以下服务端点将其发送到改造中:
public interface Api {
@NonNull
@POST("cart/payment")
@Headers({"Content-Type:application/json"})
Observable<ResponseBody> postPaymentEvent(@Body Map<String, Object> body);
}
我尝试了以下内容:
Map<String, Object> map = new HashMap<>();
JSONObject json = new JSONObject();
json.put("id_object", 88);
json.put("id_store", 43);
json.put("type", "payment");
map.put("action", "view");
map.put("id_invoice", 1234);
map.put("data", json); //this is wrong. it creates the following response with a nameValuePairs field, which is not what i want:
体:
{
"action": "page_view",
"id_invoice": "1234",
"data": {
"nameValuePairs": {
"id_object": 88,
"id_store": 43,
"type": "view"
}
}
}
答案 0 :(得分:0)
这样做:
JSONObject dataJson = new JSONObject();
try {
JSONObject parentJson = new JSONObject();
dataJson.accumulate("id_object", 88);
dataJson.accumulate("id_store", 43);
dataJson.accumulate("type", "payment");
parentJson.accumulate("id_invoice",1234);
parentJson.accumulate("action","viewed");
parentJson.put("data",dataJson);
Log.d("Main Screen ",parentJson.toString());
} catch (JSONException e) {
e.printStackTrace();
}
它会产生这个:
{
"id_invoice": 1234,
"action": "viewed",
"data": {
"id_object": 88,
"id_store": 43,
"type": "payment"
}
}