2
votes

I have a model that looks like this (Play 2.1.1 java ebean)

@Entity
public class Link extends Model {
    @Id
    public Long id;

    @Lob
    public String points;
}

where points is a raw json string that contains x, y coordinates in an array.

I don't want to have to deserialize it to an array of Points, because it's only going to be used for the UI. and thus, I would like to save it to a text field in the database

I want the property points to get serialized as a json array when sent over the wire to the frontend and I want the frontend to be able to send an json array and make it into a string again.

In the controller:

// Serialize
List<Link> links = Link.findAll();
return ok(Json.toJson(links));

// Deserialize
Link link = Json.fromJson(request().body().asJson(), Link.class);

How should I do this?

Custom serializer, deserializer?

@JsonRawValue?

Any other annotation?

1
Just a little comment: You can send it as a JSON string, just as it is, and have it deserialized in your frontend very easily using JavaScript (or jQuery, for instance), if that is your case. Does that suit your needs? It's just one extra line of code in your client... - Azurlake
I'm using angular.js and ngResource which means that I don't do the requests by my self, so I'd rather not resort to that. but thanks anyways :) - Leon Radley

1 Answers

3
votes

The answer was a lot simpler than you would suspect.

@Lob
public String points;

public JsonNode getPoints() {
    return Json.parse(StringUtils.isBlank(points) ? "[]" : points);
}

@JsonSetter
public void setPoints(JsonNode json) {
    points = json.toString();
}

Though I'm not that fond of getter's and setter's it works.

If anyone has a better solution that is more generic, feel free to post another answer :)