sw00
sw00

Reputation: 980

Play! framework renderJson not exposing particular fields

I'm trying to expose a dynamic(transient) field in my models via renderJson(), but it's not working. Here's an example:

@Entity
public class Room extends Model {

  public String name;
  public String code;
  @Transient
  public List<Booking> bookings;

  @Transient
  @Expose
  public String resource_uri;

  public Room(String name, String code) {
    this.name = name;
    this.code = code;
  }

  public List<Booking> getBookings() {
    return Booking.find("byRoom", this).fetch();
  }

  public String getResource_uri(){
    return "/api/room/" + this.id; //the uri is evaluated dynamically.
  }

A call to renderJson(Room.findById(2)) renders this as a response:

{"name":"Room B","code":"R-B","id":2}

The resource_uri field is missing. The @Expose annotation seems to do nothing. And I can't view renderJson's declaration since the framework generates all the code by annotations.

Upvotes: 2

Views: 2953

Answers (3)

Karthik Sankar
Karthik Sankar

Reputation: 896

Play framework 2.0 uses jackson to make a json string. Use @JsonIgnore annotation on the fields, that you do not want to expose

Upvotes: 1

alfonso.kim
alfonso.kim

Reputation: 2900

Play! uses Gson. It doesn´t serialize transient fields.

Take a look at https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples

I like Gson because it comes with Play! out of the box. You can build your own, adapter, something like:

public class RoomAdapter implements JsonDeserializer<Room>, JsonSerializer<Room> {
    public Room deserialize(JsonElement json, Type type, JsonDeserializationContext context){
        // Parse the Json to build a Room
    }

    public JsonElement serialize(Room room, Type type, JsonSerializationContext context){
        // Insert magic here!!
    }
}

Register the serializer:

Gson gson = new GsonBuilder().registerTypeAdapter(
            Room.class, new RoomAdapter()).create();

And use the gson specifying the class you want to serialize:

String jsonRoom = gson.toJson(aRoom, Room.class);
Room aRoom = gson.fromJson(jsonRoom, Room.class);

Upvotes: 1

Codemwnci
Codemwnci

Reputation: 54884

There seems to be a discrepancy in your field declarations, you have

@Transient
@Expose
public String resource_uri;

Yet, you also have

public String getResource_uri(){
   return "/api/room/" + this.id; //the uri is evaluated dynamically.
}

This would suggest that your resource_uri field is forever null?

Upvotes: 1

Related Questions