简体   繁体   English

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

[英]Retrofit: Sending POST request with JSON Array

I have JsonElement jsonElement object which I receive as response from my another GET request.我有JsonElement jsonElement对象,我从另一个 GET 请求收到它作为响应。 jsonElement.toString(); looks like JSON array:看起来像 JSON 数组:

[{"Id":493,"Number":"380936831127","FriendNumber":"380682140976"},{"Id":494,"Number":"380936831127","FriendNumber":"380638254108"}]

I need to send this string via another POST request using Retrofit.我需要使用 Retrofit 通过另一个 POST 请求发送此字符串。 How can I send jsonElement or String object via POST request?如何通过 POST 请求发送 jsonElement 或 String 对象? How should look declaration of my method?我的方法的声明应该如何看? For example:例如:

 @POST("/api/geo/getLoc")
    public void getFriendsLocation(/* something */,  Callback<JsonElement> response);

If you are sending data over request body your implementation should be like this:如果您通过请求正文发送数据,您的实现应该是这样的:

  1. Define model according to fields (CaseSensitive "Name" -> String Name etc )根据字段定义模型(区分大小写的“名称”-> 字符串名称等)
  2. set your api function also like that也像这样设置你的api函数

    @POST("/api/geo/getLoc") public void getFriendsLocation(@Body YourClass classObject, Callback<JsonElement> response);
  3. Use directly your created class object on post request在发布请求时直接使用您创建的类对象

    getFriendsLocation(yourClassObjectThatIncludesFields, new Callback .... )

If your sending data over params You can do this with Gson.如果您通过 params 发送数据,您可以使用 Gson 执行此操作。

  1. Lets say you have a class that have fields like id , number and FriendNumber.Define a function :假设您有一个包含 id 、 number 和 FriendNumber 等字段的类。定义一个函数:

     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); }
  2. set your api function also like that也像这样设置你的api函数

    @POST("/api/geo/getLoc") public void getFriendsLocation(@QueryMap Map<String, Object>, Callback<JsonElement> response);
  3. When you are sending post request create object from your fields call this function like below here当您从您的字段发送 post 请求创建对象时,请调用此函数,如下所示

    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.我假设您需要发送身体,因此请尝试第一种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM