Customizing JSON serialization in Play

后端 未结 3 868
灰色年华
灰色年华 2020-12-10 23:29

I\'m using renderJSON(Object) to return some objects as JSON values, and it\'s working fine except for one field. Is there an easy way to add in that one field

3条回答
  •  渐次进展
    2020-12-10 23:43

    Play uses GSON to build the JSON string. If your one field is a specific object type, then you can easily do this by providing a customised serialisation for that type. See the documentation here

    http://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserializ

    However, if it is an Integer class for example, that you want to work in one way for one, and another way for another, then you may have a little more difficulty.

    Example

    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(SpecificClass.class, new MySerializer());
    
    private class MySerializer implements JsonSerializer {
      public JsonElement serialize(SpecificClass src, Type typeOfSrc, JsonSerializationContext context) {
        String res = "special format of specificClass"
        return new JsonPrimitive(res);
      }
    }
    

提交回复
热议问题