玩!框架renderJson不暴露特定字段

时间:2011-09-09 11:58:03

标签: java json annotations playframework gson

我试图通过renderJson()在我的模型中公开一个动态(瞬态)字段,但它不起作用。这是一个例子:

@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.
  }

renderJson(Room.findById(2))的调用将此作为回复呈现:

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

缺少resource_uri字段。 @Expose注释似乎什么都不做。而且我无法查看renderJson的声明,因为框架通过注释生成所有代码。

3 个答案:

答案 0 :(得分:1)

您的字段声明中似乎存在差异,您有

@Transient
@Expose
public String resource_uri;

然而,你也有

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

这表明你的resource_uri字段永远为空?

答案 1 :(得分:1)

播放!使用Gson。它没有序列化瞬态字段。

查看https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples

我喜欢Gson,因为它带有Play!盒子外面。 您可以构建自己的适配器,例如:

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!!
    }
}

注册序列化程序:

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

并使用指定要序列化的类的gson:

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

答案 2 :(得分:1)

Play framework 2.0使用jackson制作一个json字符串。在字段上使用@JsonIgnore注释,您不希望公开

相关问题