开发者

Play! framework renderJson not exposing particular fields

开发者 https://www.devze.com 2023-04-04 06:09 出处:网络
I\'m trying to expose a dynamic(transient) field in my models via renderJson(), but it\'s not working. Here\'s an example:

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(){
    retur开发者_开发知识库n "/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.


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);


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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号