java 嵌套json类型不会在jersey中序列化

gr8qqesn  于 2023-02-14  发布在  Java
关注(0)|答案(1)|浏览(104)
    • bounty将在6天后过期**。回答此问题可获得+100声望奖励。James Wierzba希望引起更多人关注此问题。

我正在运行一个dropwizard/jersey java restful网络应用程序。
我在api.yaml中定义了一个端点,如下所示:

/v1/event:
  post:
    summary: receive a event
    operationId: receiveEvent ## this value names the generated Java method
    parameters:
      - name: event
        in: body
        schema:
          $ref: "#/definitions/Event"
      responses:
        # ...

Stream:
  properties:
    vendor:
      type: "string"
Event:
  eventCity:
    type: "string"
  streams:
    type: "array"
    items:
      $ref: "#/definitions/Stream"

端点定义如下

@POST
    @Consumes({ "application/json", "application/x-protobuf" })
    @Produces({ "application/json", "application/x-protobuf" })
    @Path("/event")
    void receiveEvent(
            @Suspended AsyncResponse response,
            @Valid Event.EventModel  event
    );

当发出json POST请求时,我无法获取streams字段以获取序列化/反序列化属性。
这是有效载荷

{
  "eventCity": "San Diego", 
  "streams": {
    "vendor": "CBS"
  }
}

我用curl这样测试

curl -X POST -H "Content-Type: application/json" -d '{"eventCity": "San Diego", "streams": {"vendor": "CBS"}}' https://localhost:8990/v1/event

在服务器请求处理程序中:

@Override
public void receiveEvent(AsyncResponse response, Event.EventModel event) {
  System.out.println(event.getEventCity());
  System.out.println(event.getStreamCount()); // <-- this returns 0? why is the inner 'streams' list not getting serialized? it should have one element
}

并且输出:

San Diego
0

另一个观察结果是,当我发布相同的帖子,但是使用protobuf有效载荷时,它工作了。
protobuf是这样生成的

// create proto
Stream.StreamModel stream = Stream.StreamModel.newBuilder()
        .setVendor("CBS")
        .build();
Event.EventModel event = Event.EventModel.newBuilder()
        .setEventCity("San Diego")
        .addStream(stream)
        .build();

// write to file
FileOutputStream fos = new FileOutputStream("/Users/jameswierzba/temp/proto.out");
stream.writeTo(fos);

端点中的输出符合预期:

San Diego
1
lmyy7pcs

lmyy7pcs1#

考虑事件。流具有类型:“数组”有效负载应为:

{
  "eventCity": "San Diego", 
  "streams": [
       {
         "vendor": "CBS"
       }
   ]
}

不是

{
  "eventCity": "San Diego", 
  "streams": {
    "vendor": "CBS"
  }
}

相关问题