[英]POST request of an array into JSON with Retrofit 2 Android
我是android的初學者。我想在帖子中添加評論,我嘗試了很多解決方案但都沒有用。 當我在 postman 中測試 API 時,它可以工作,但我不知道如何在 android 中進行測試。
這是我在 nodejs 中的實體
_id: mongoose.Schema.Types.ObjectId,
text: String,
likes: { type: Number, default: 0 },
date: Date,
image: String,
idUser: String,
comments: [{
text: String,
date: Date,
idUser: String,
}],
這是API
router.post('/comments/:idPost', (req, res, next) => {
const id = req.params.idPost;
Post.updateOne({ _id: id }, {
$addToSet: {
comments: [{
text: req.body.comments.text,
date: Date.now(),
idUser: req.body.comments.idUser
}],
}
}, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
});
});
這是我在 Java 中的實體
@SerializedName("_id")
private String idPost;
@SerializedName("text")
private String text;
@SerializedName("likes")
private int likes;
@SerializedName("date")
private Date date;
@SerializedName("image")
private String image;
@SerializedName("idUser")
private String idUser;
@SerializedName("comments")
private ArrayList<Comment> CommentArrayList;
public static class Comment {
@SerializedName("_id")
private String idComment;
@SerializedName("text")
private String text;
@SerializedName("date")
private Date date;
@SerializedName("idUser")
private String idUser; }
}
這是我提出的要求
@POST("/posts/comments/{idPost}")
Call<ResponseBody> addComment(@Path("idPost") String idPost, @Body JSONObject comment);
我不能很好地理解你的問題。 我可以解釋如何使用 retrofit2 將數據發送到節點 JS
android,在Retrofit界面添加這一行
@POST("/user/phone/verify")
Call<Void> addNewComment(@Body HashMap<String, String> map);
並在此處添加有關評論的詳細信息:
HashMap<String,String> map = new HashMap<>();
map.put("id","your id");
map.put("image","your image");
map.put("comment","your comment");
map.put("password",password);
然后這段代碼調用 post 方法作為上面的 HashMap as body
Call<Void> call = retrofitInterface.executeSignUp(map);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
if (response.code()==200){
//Success
}else {
//An error ocuurred
}
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
Log.e("ServerCallback", "onFailure: ",t);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.