0

I'm extending JsonSerializer to override it's serialize method like so:

public class UserSerializer extends JsonSerializer<User> {
    @Override
    public void serialize(User user, JsonGenerator jsonGenerator,
                      SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeObjectField("timestamp", user.getTimestamp());
        jsonGenerator.writeStringField("caption", user.getCaption());
        jsonGenerator.writeEndObject();
    }
}

User is defined as such:

@JsonSerialize(using = UserSerializer.class)
@Document
public class User {

    @NotNull
    @Id
    private String id;

    @NotNull
    private Date timestamp;

    private String caption;

    public Date getTimestamp() {
        return timestamp;
    }

    public String getCaption() {
        return caption;
    }

    public void setCaption(String caption) {
        this.caption = caption;
    }

    public void setTimestamp(Date timestamp) {
      this.timestamp = timestamp;
    }
}

And I'm calling the following controller method, in order for it to return the users:

@RequestMapping(value = "/users", method = RequestMethod.GET)
public ResponseEntity<PagedResources<User>> findAll(Pageable pageable) {
    Page<User> results = userService.findAll(pageable);
    return new ResponseEntity(pagedAssembler.toResource(results), HttpStatus.OK);
}

But it returns the paged content like:

{
"_embedded" : {
    "users" : [ {
      "content" : {
        "timestamp" : "2016-02-07T21:32:22.830+0000",
        "caption" : "hi"
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/....."
    }
  },
  "page" : {
    "size" : 5,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}

As you can see, the returned data is inside a "content" key. I don't want this to happen, how can I make the data appear embedded in the "users" key? (This is the default when not overriding the serialize method)

Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • Can you show your user class and also parent class and probably how you register your serializer? Because if you register your serializer correctly and parent class looks like `OuterObject{ public User[] users;}` your serializer should work just fine. – varren Apr 17 '16 at 12:33
  • @varren updated. There isn't a parent class as such, I'm just calling the controller method, which performs a findAll in the user mongo repository. – Tometoyou Apr 17 '16 at 12:46
  • Ahh hold on, I may have struck gold. Someone has had the same thing as me, I'll check out the answer and update on here if it works: http://stackoverflow.com/questions/22613143/different-json-output-when-using-custom-json-serializer-in-spring-data-rest – Tometoyou Apr 17 '16 at 12:50
  • Yep it fixed the problem :) – Tometoyou Apr 17 '16 at 13:21

0 Answers0