JetStream
JetStream

Reputation: 550

JSON - Get Jackson to use the JsonProperty when serializing

Is it possible to configure in a simple way such that Jackson (used in a Spring Boot REST service) uses the JsonProperty attribute when serializing the object?

There's a Spring Boot REST client talking to a Spring Boot REST service. The REST service is generating the JSON using the field names, but the REST client, when it receives the JSON, is trying to parse it using the value specified in the @JsonProperty annotation.

I'm at a loss to explain what is causing it to take difference approaches during serialization/deserialization and what can be done to make them talk in the same speak. I hope this is a simple configuration that can be set somewhere.

JSON received by the client

16:13:47.491 [main] INFO TokenServiceImpl - AccessToken received: "token":"2YotnFZFEjr1zCsicMWpAA","expiresIn":3600,"refreshToken":"YES","tokenType":"example"}

Exception thrown

Caused by: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "token" (C lass org.jboss.resteasy.skeleton.key.representations.AccessTokenResponse), not marked as ignorable  at [Source: java.io.ByteArrayInputStream@2e9820ae; line: 1, column: 11] (through reference chain: o rg.jboss.resteasy.skeleton.key.representations.AccessTokenResponse["token"])
        at org.codehaus.jackson.map.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyExcep tion.java:53)

REST Server code

import org.jboss.resteasy.skeleton.key.representations.AccessTokenResponse;

@RequestMapping(value = "/token", method = RequestMethod.POST)
public @ResponseBody AccessTokenResponse getToken(@RequestBody String requestBody)
{
  System.out.println("Request Body received:\n" + requestBody);

  AccessTokenResponse response = new AccessTokenResponse();
  response.setToken("2YotnFZFEjr1zCsicMWpAA");
  response.setTokenType("example");
  response.setExpiresIn(3600L);
  response.setRefreshToken("YES");

  return response;
}

Class being serialized

package org.jboss.resteasy.skeleton.key.representations;

public class AccessTokenResponse
{
  @JsonProperty("access_token")
  protected String token;

  ...

  public String getToken()
  {
    return token;
  }
  ...
}

Upvotes: 0

Views: 1133

Answers (1)

DanielM
DanielM

Reputation: 4033

You can set the property name on the getToken method instead and spring will use it:

  protected String token;

  ...
  @JsonProperty("access_token")
  public String getToken()
  {
    return token;
  }

Upvotes: 1

Related Questions