改造:使用 JSON 数组发送 POST 请求 [英] Retrofit: Sending POST request with JSON Array
问题描述
我有 JsonElement jsonElement
对象,我从另一个 GET 请求收到它作为响应.jsonElement.toString();
看起来像 JSON 数组:
I have JsonElement jsonElement
object which I receive as response from my another GET request. jsonElement.toString();
looks like JSON array:
[{"Id":493,"Number":"380936831127","FriendNumber":"380682140976"},{"Id":494,"Number":;380936831127","FriendNumber":"380638254108"}]
我需要使用 Retrofit 通过另一个 POST 请求发送此字符串.如何通过 POST 请求发送 jsonElement 或 String 对象?我的方法的声明应该如何看?例如:
I need to send this string via another POST request using Retrofit. How can I send jsonElement or String object via POST request? 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:
- 根据字段定义模型(区分大小写的名称"-> 字符串名称等)
同样设置你的api函数
- Define model according to fields (CaseSensitive "Name" -> String Name etc )
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.
假设您有一个包含 id 、 number 和 FriendNumber 等字段的类.定义一个函数:
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.
这篇关于改造:使用 JSON 数组发送 POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!