在Apache CXF REST服务中将JSON数据作为请求正文提交

时间:2021-06-07 19:34:36

I know this has been asked before, but going through multiple answers did not help me solve my issue. So here it is: I'm a newbie trying to create a REST service using Apache CXF. I'm trying to write a POST method and send the data as JSON in the request body(using POSTMAN in Google Chrome to do this).

我知道之前已经问过,但是通过多个答案并没有帮助我解决我的问题。所以这就是:我是一个尝试使用Apache CXF创建REST服务的新手。我正在尝试编写POST方法并在请求正文中将数据作为JSON发送(使用Google Chrome中的POSTMAN来执行此操作)。

My interface looks something like this:

我的界面看起来像这样:

     @Path("/")
     @Produces("application/json")
     public interface MyService{

         @POST
         @Path("/addNote/{id}")
         @Consumes("application/json")
         NoteResponse addNote(@PathParam("id") Long id, @QueryParam("note")Note note);

         // OTHER @GET METHODS THAT WORK WELL
     }

My implmentation:

我的诽谤:

    @WebService(name = "testservice")
    public class MyServiceImpl implements MyService{

        @Override
        public NoteResponse addNote(Long id, Note note){
            // SOME IMPLEMENTATION
        }
        // OTHER @GET METHOD IMPLEMENTATIONS THAT WORK
    }

I've read in some answers that I do not need the @QueryParam on my note annotation, instead just put and @XMLRootElement on my Note class, but doing that and trying going on localhost:8080/rest/addNote/1 will NOT call my addNote method.

我已经读过一些答案,我不需要在我的note注释上使用@QueryParam,而只是在我的Note类上放置@XMLRootElement,但是这样做并尝试继续使用localhost:8080 / rest / addNote / 1将不会调用我的addNote方法。

The problem I am facing now is that the note parameter comes null.

我现在面临的问题是note参数为空。

Here's the JSON I've sent via POSTMAN:

这是我通过POSTMAN发送的JSON:

    {
        "note":{
            "id": 4958,
            "anotherId": 7886,
            "comment": "salut",
            "mail": "mail@mail.com",
            "gregorianDate": "01-01-2016",
            "type": "INFO"
        }
    }

1 个解决方案

#1


2  

Please try changing your interface definition of API addNote to this:

请尝试将API addNote的接口定义更改为:

NoteResponse addNote(@PathParam("id") Long id, Note note);

And send this JSON string via POSTMAN:

并通过POSTMAN发送此JSON字符串:

        {
            "id": 4958,
            "anotherId": 7886,
            "comment": "salut",
            "mail": "mail@mail.com",
            "gregorianDate": "01-01-2016",
            "type": "INFO"
        }

This should work.

这应该工作。

#1


2  

Please try changing your interface definition of API addNote to this:

请尝试将API addNote的接口定义更改为:

NoteResponse addNote(@PathParam("id") Long id, Note note);

And send this JSON string via POSTMAN:

并通过POSTMAN发送此JSON字符串:

        {
            "id": 4958,
            "anotherId": 7886,
            "comment": "salut",
            "mail": "mail@mail.com",
            "gregorianDate": "01-01-2016",
            "type": "INFO"
        }

This should work.

这应该工作。