POST 使用 Retrofit 2 Android 请求数组进入 JSON

POST request of an array into JSON with Retrofit 2 Android

我是 android 的初学者。 我想在 post 中添加评论,我尝试了很多解决方案,但 none 有效。 当我在 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);
            }
        });