gpt4 book ai didi

android - retrofit 2 - 如何传递 POST json 对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:25:54 25 4
gpt4 key购买 nike

所以,我有一个自定义对象列表,我需要一个像这样的 JSON:

{
"surveys": [{
"survey": {
"code": "05052017153632",
"date": "05/05/2017 15:36:32",
"device_id": 1,
"questions_attributes": [{
"kind": "string",
"label": "Você encontrou tudo o que procurava?",
"value": "Infelizmente, não"
}, {
"kind": "string",
"label": "Em qual departamento você não encontrou o produto?",
"value": "FERRAMENTAS, TAPETES"
}, {
"kind": "string",
"label": "Deseja que a Havan entre em contato com você?",
"value": "Não informado"
}, {
"kind": "string",
"label": "Nome",
"value": "Não informado"
}, {
"kind": "string",
"label": "E-mail",
"value": "Não informado"
}, {
"kind": "string",
"label": "Telefone",
"value": "Não informado"
}]
}
}]}

但我不知道如何使用 Gson 来完成它。我正在使用 Retrofit 2,需要将此 JSON 传递到正文请求中。有什么想法吗?

最佳答案

是的,您需要将此 JSON 传递到正文请求中。

改造接口(interface):

public interface RetrofitInterface<R extends RetrofitClass> {
@Headers({"Content-Type: application/json", "Cache-Control: max-age=640000"})
@POST("v1/auth/")

public Call<ResponseBody> callLogin(@Query("key") String key, @Body LoginModel body);
@Headers({"Content-Type: application/json", "Cache-Control: max-age=640000"})

public static final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConstants.mBaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}

API调用 Activity :

使用@Body 参数将json 对象传递到body 请求中。

这里你可以在http://www.jsonschema2pojo.org/中创建gson模型类使用该 json 请求格式将 json 转换为 gson。

之后,使用该 gson pojo 类设置值,并将 json 对象传递给改造中的 body 请求。

例如:

登录模型:

public class LoginModel {
@SerializedName("username")
private String username;
@SerializedName("password")
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

用 pojo 类设置值:

LoginModel model_obj = new LoginModel();
mModel_obj.setUsername(mUsername);
mModel_obj.setPassword(mPassword);

API调用:

Call<ResponseBody> call = service.callLogin(AppConstants.mApiKey, model_obj);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});

关于android - retrofit 2 - 如何传递 POST json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43853436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com