【问题标题】:retrofit map as body - how to post map with inner json object改造地图作为主体 - 如何使用内部 json 对象发布地图
【发布时间】:2018-03-08 15:02:32
【问题描述】:

Retrofit2 我将如何使用具有内部 json 的地图 json 主体发布。让我给你举个例子:

{
    "id_invoice": 1234,
    "action": "viewed",
    "data": {
        "id_object": 88,
        "id_store": 43,
        "type": "payment"
     }
}

注意“数据”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"
         }
    }
}

【问题讨论】:

    标签: android json retrofit


    【解决方案1】:

    这样做:

     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"
      }
    }
    

    【讨论】:

    • 我需要在 Hashmap 中使用它。
    • 您是否在哈希图中添加了其他内容?
    • 没有。我只需要将那个 json 放在地图中。显然我可以使用一个类和gson。但正在尝试使用地图
    猜你喜欢
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 2017-02-24
    • 1970-01-01
    • 2016-02-01
    • 2017-11-15
    • 1970-01-01
    相关资源
    最近更新 更多