发送空的 JSON 对象到 API。

huangapple go评论80阅读模式
英文:

Send empty JSON objet to API

问题

以下是翻译好的部分:

出于实验目的,我必须发送一个包含其他对象的 JSON 对象,其中一个对象没有属性(为空),如下所示:

{
    "id": "00u12e3knx76B4PNS4x7",
    "scope": "USER",
    "credentials": {
        "userName": "some@email.com"
    },
    "profile": {}
}

我正在使用 Java Jersey 和 POJO 从 JSON 负载生成 Java 类,但我无法找到在这种情况下如何发送与我的 API 要求匹配的内容。

这是我的代码示例:

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response eventHook(String body, @HeaderParam("Pass") String password) {
    ObjectMapper objectMapper = new ObjectMapper();
    RequestPayload requestPayload = new RequestPayload();

    writeLogger(body);

    try {
        requestPayload = objectMapper.readValue(body, RequestPayload.class);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }

    EventsItem event = requestPayload.getData().getEvents().get(0);

    TargetItem targetItem = event.getTarget().get(2);

    RequestApiAssignUser user = new RequestApiAssignUser();

    Credentials credentials = new Credentials();
    credentials.setUserName("id");
    user.setId(getUser.getId());
    user.setScope("USER");
    user.setCredentials(credentials);

    Profile profile = new Profile();
    user.setProfile(profile);

    Response postResponse = ClientBuilder.newClient()
            .target(API_URL)
            .path("apps/" + getApps("0oa13t5dqnkYGDZEd4x7") + "/users")
            .request(MediaType.APPLICATION_JSON)
            .header(HttpHeaders.AUTHORIZATION, "SSWS " + API_TOKEN)
            .post(Entity.entity(user, MediaType.APPLICATION_JSON));

    String responseAPI = postResponse.readEntity(String.class);

    return Response.status(200).entity(responseAPI).build();

这是由于无法序列化 Profile 对象而引起的错误,因为它没有属性:

> jakarta.ws.rs.ProcessingException:
> com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No
> serializer found for class
> Payload.Api.Apps.Post.Assign.Request.Profile and no properties
> discovered to create BeanSerializer (to avoid exception, disable
> SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain:
> Payload.Api.Apps.Post.Assign.Request.RequestApiAssignUser["profile"])

谢谢!
英文:

For lab purpose I have to send a JSON object containing others objects and one of them has no property (empty) as you can see :

{
     "id": "00u12e3knx76B4PNS4x7",
     "scope": "USER",
     "credentials": {
     "userName": "some@email.com"
     },
     "profile": {}
}

I'm using Java Jersey and POJO to generate Java classes from JSON payloads but I cannot find what to send in this case match my API requirement.

Here is my code sample :

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response eventHook(String body, @HeaderParam("Pass") String password) {
    ObjectMapper objectMapper = new ObjectMapper();
    RequestPayload requestPayload = new RequestPayload();

    writeLogger(body);

    try {
        requestPayload = objectMapper.readValue(body, RequestPayload.class);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }

    EventsItem event = requestPayload.getData().getEvents().get(0);

    TargetItem targetItem = event.getTarget().get(2);

    RequestApiAssignUser user = new RequestApiAssignUser();

    Credentials credentials = new Credentials();
    credentials.setUserName("id");
    user.setId(getUser.getId());
    user.setScope("USER");
    user.setCredentials(credentials);

    Profile profile = new Profile();
    user.setProfile(profile);

    Response postResponse = ClientBuilder.newClient()
            .target(API_URL)
            .path("apps/" + getApps("0oa13t5dqnkYGDZEd4x7") + "/users")
            .request(MediaType.APPLICATION_JSON)
            .header(HttpHeaders.AUTHORIZATION, "SSWS " + API_TOKEN)
            .post(Entity.entity(user, MediaType.APPLICATION_JSON));

    String responseAPI = postResponse.readEntity(String.class);

    return Response.status(200).entity(responseAPI).build();

Here is the error due to the imposssibility to serialize Profile Object because it has no properties :

> jakarta.ws.rs.ProcessingException:
> com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No
> serializer found for class
> Payload.Api.Apps.Post.Assign.Request.Profile and no properties
> discovered to create BeanSerializer (to avoid exception, disable
> SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain:
> Payload.Api.Apps.Post.Assign.Request.RequestApiAssignUser["profile"])

Thanks !

答案1

得分: 2

错误提示你在ObjectMapper上禁用SerializationFeature.FAIL_ON_EMPTY_BEANS属性。通常情况下,要通过实现ContextResolver来配置ObjectMapper与Jersey一起使用。底层使用的Jackson ObjectMapper将查找此解析器并配置该属性。

但在这种情况下,你的代码中已经在使用一个mapper。所以我只会配置那个mapper,然后将User对象序列化为字符串,并将该JSON字符串用作实体

objectMapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);

然后在客户端代码底部,将User序列化为字符串。

String userJson = objectMapper.writeValueAsString(user);
Response postResponse = ClientBuilder.newClient()
            ...
            .post(Entity.entity(userJson, MediaType.APPLICATION_JSON));

在其他情况下,如果你之前没有ObjectMapper,你将像我上面提到的那样实现一个ContextResolver

public class ObjectMapperResolver implements ContextResolver<ObjectMapper> {

    private final ObjectMapper mapper = new ObjectMapper();

    public ObjectMapperResolver() {
        mapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);
    }

    @Override
    public ObjectMapper getContext(Class<?> cls) {
        return mapper;
    }
}

然后你会在客户端中注册这个解析器。

Response postResponse = ClientBuilder.newClient()
        .register(ObjectMapperResolver.class)
        ...
英文:

The error is telling you to disable the SerializationFeature.FAIL_ON_EMPTY_BEANS property on the ObjectMapper. Normally to configure the ObjectMapper with Jersey, you would implement a ContextResolver. The the Jackson ObjectMapper that's used under the hood would look this resolver up and configure the property.

But in this case, you already are using a mapper in your code. So I would just configure that mapper and then serialize the User object into a String and use that JSON string as the entity

objectMapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);

Then at the bottom before your client code just serialize the User to a string.

String userJson = objectMapper.writeValueAsString(user);
Response postResponse = ClientBuilder.newClient()
            ...
            .post(Entity.entity(userJson, MediaType.APPLICATION_JSON));

In other cases, if you did not already have an ObjectMapper, you would implement a ContextResolver as I mentioned above.

public class ObjectMapperResolver implements ContextResolver&lt;ObjectMapper&gt; {

    private final ObjectMapper mapper = new ObjectMapper();

    public ObjectMapperResolver() {
        mapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);
    }

    @Override
    public ObjectMapper getContext(Class&lt;?&gt; cls) {
        return mapper;
    }
}

Then you would register this with the client

Response postResponse = ClientBuilder.newClient()
        .register(ObjectMapperResolver.class)
        ...

答案2

得分: 0

你创建了 Credentials() 对象,这是一个空对象,但是你设置了 userName,现在它不再是空的。Credentials 对象有一个 userName 变量。但是你创建的 Profile() 对象是空的。而且你没有给这个 Profile() 对象设置任何变量。你将 Profile() 对象设置为了空的 Profile() 对象。你需要设置一个真实的变量。

英文:

You created Credentials() object and this is a empty object but you setted userName, now is not empty. Credentials object have a userName variable. But your created Profile() object is empty. And you did not set any variable to this Profile() object. You setted Profile() object to empty Profile() object. You need set a real variable.

huangapple
  • 本文由 发表于 2020年10月8日 22:55:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64265220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定