且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

改造:使用 JSON 数组发送 POST 请求

更新时间:2023-01-17 08:35:27

如果您通过请求正文发送数据,您的实现应该是这样的:

If you are sending data over request body your implementation should be like this:

  1. 根据字段定义模型(区分大小写的名称"-> 字符串名称等)
  2. 同样设置你的api函数

  1. Define model according to fields (CaseSensitive "Name" -> String Name etc )
  2. set your api function also like that

@POST("/api/geo/getLoc")
public void getFriendsLocation(@Body YourClass classObject,   Callback<JsonElement> response);

  • 在发布请求时直接使用您创建的类对象

  • Use directly your created class object on post request

    getFriendsLocation(yourClassObjectThatIncludesFields, new Callback .... )
    

  • 如果您通过参数发送数据,您可以使用 Gson 执行此操作.


    If your sending data over params You can do this with Gson.

    1. 假设您有一个包含 id 、 number 和 FriendNumber 等字段的类.定义一个函数:

    1. Lets say you have a class that have fields like id , number and FriendNumber.Define a function :

    public static Map<String, Object> getMapFromObject(Object o) {
        Gson gson = new Gson();
        Type stringObjectMap = new TypeToken<Map<String, Object>>() {
         }.getType();
        return gson.fromJson(gson.toJson(o), stringObjectMap);
    }
    

  • 同样设置你的api函数

  • set your api function also like that

    @POST("/api/geo/getLoc")
    public void getFriendsLocation(@QueryMap Map<String, Object>,     Callback<JsonElement> response);
    

  • 当您从您的字段发送 post 请求时,请在此处调用此函数,如下所示

  • When you are sending post request create object from your fields call this function like below here

    getFriendsLocation(getMapFromObject(yourClassObjectThatIncludesFields), new Callback .... )
    

  • 我没有编写包含类定义和回调函数的完整代码,因为它们取决于您的自定义.我假设您需要发送正文,因此请尝试第一种方式.

    I didnt write whole code which includes class definition and Callback function because they are up to your customization. I assume that you need to send over body so try the first way.