在 Play 中自定义 JSON 序列化

发布于 2024-10-08 20:29:43 字数 101 浏览 2 评论 0原文

我正在使用 renderJSON(Object) 将一些对象作为 JSON 值返回,并且除了一个字段之外它工作正常。有没有一种简单的方法可以添加该字段,而无需手动创建整个 json 模板?

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 without having to manually create the whole json template?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烟燃烟灭 2024-10-15 20:29:43

Play 使用 GSON 构建 JSON 字符串。如果您的一个字段是特定的对象类型,那么您可以通过为该类型提供自定义序列化来轻松完成此操作。请参阅此处的文档

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

但是,如果它是一个 Integer 类,那么您希望以一种方式工作,换一种方式换另一种方式,那么你可能会遇到更多的困难。

例子

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(SpecificClass.class, new MySerializer());

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

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<DateTime> {
  public JsonElement serialize(SpecificClass src, Type typeOfSrc, JsonSerializationContext context) {
    String res = "special format of specificClass"
    return new JsonPrimitive(res);
  }
}
定格我的天空 2024-10-15 20:29:43

只需做一个

JsonElement elem = new Gson().toJsonTree(yourObject);
JsonObject obj = elem.getAsJsonObject();
obj.remove("xxx");
obj.addProperty("xxx", "what you want"); 
// other stuff ... 
renderJSON(obj.toString());

等等。

Simply do a

JsonElement elem = new Gson().toJsonTree(yourObject);
JsonObject obj = elem.getAsJsonObject();
obj.remove("xxx");
obj.addProperty("xxx", "what you want"); 
// other stuff ... 
renderJSON(obj.toString());

etc.

淡淡の花香 2024-10-15 20:29:43

在评估了播放框架之后,我们遇到了一个障碍,并决定为外部 API 序列化 JSON。很多文章建议在游戏中使用 Lift 框架,这看起来像是额外的开销。在尝试了游戏框架中的一些框架/模块后,我和大学决定编写一个轻量级代码块来满足我们的需求。

case class User (
    user_id:        Int,
    user_name:      Option[String],
    password:       Option[String],
    salt:           Option[String]
) extends Serializable {
  def toXml = 
    <user>
          <user_id>{user_id}</user_id>
          <user_name>{user_name.getOrElse("")}</user_name>
    </user>

  override def toJson =
    "{" + JSON.key("user_id") + JSON.value(user_id) + ", " + JSON.key("user_name") + JSON.value(user_name) + "}"
}

class Serializable {
  def toJson = ""
}

object JSON {
  def key(x:String) = value(x) + ": "

  def value(x:Any):String = {
    x match {
      case s:String => "\"" + s + "\""
      case y:Some[String] => value(y.getOrElse(""))
      case i:Int => value(i.toString)
      case s:Serializable => s.toJson
      case xs:List[Any] => "[" + xs.map(x => value(x)).reduceLeft(_ + ", " + _) + "]"
    }
  }
}
def searchUserByName(user_name: String) = {
        (for (
            u <- Users if u.user_name.like(("%"+user_name+"%").bind)
        ) yield u.*)
        .list
        .map(User.tupled(_))
    }

    def toXml(users:List[User]) = {
        <users>
            { users.map(u => u.toXml) }
        </users>
    }

    def toJson(users:List[User]) = {
      "[" + users.map(u => u.toJson).reduceLeft(_ + ", " + _) + "]"
    }

并来自控制器。

// -- http://localhost:9000/api/users/getUser/xml
// -- http://localhost:9000/api/users/getUser/json
def getUser(requestType:String) = {
  db withSession{
    val user = Users.byUserName("King.Kong")  
    if(requestType == "xml") {
      Xml(user.toXml)
    } else {
       user.toJson
    }
  }
}

//--- http://localhost:9000/api/users/searchuser/xml
//--- http://localhost:9000/api/users/searchuser/json
def searchUser(requestType:String) = {

  db withSession{
    val users = Users.searchUserByName("Doctor.Spoc")  
    if(requestType == "xml") {
      Xml(Users.toXml(users))
    } else {
        val jsonList = Users.toJson(users)
        Json(jsonList)
    }



  }

After evaluating the play framework we hit a stumbling block and decision choice on serializing JSON for an external API. Allot of articles out there suggest using the Lift framework within play which just seem like extra overhead.After trying some of the frameworks / modules with in the play framework a college and myself decided to write a light weight code block that could cater for our needs.

case class User (
    user_id:        Int,
    user_name:      Option[String],
    password:       Option[String],
    salt:           Option[String]
) extends Serializable {
  def toXml = 
    <user>
          <user_id>{user_id}</user_id>
          <user_name>{user_name.getOrElse("")}</user_name>
    </user>

  override def toJson =
    "{" + JSON.key("user_id") + JSON.value(user_id) + ", " + JSON.key("user_name") + JSON.value(user_name) + "}"
}

class Serializable {
  def toJson = ""
}

object JSON {
  def key(x:String) = value(x) + ": "

  def value(x:Any):String = {
    x match {
      case s:String => "\"" + s + "\""
      case y:Some[String] => value(y.getOrElse(""))
      case i:Int => value(i.toString)
      case s:Serializable => s.toJson
      case xs:List[Any] => "[" + xs.map(x => value(x)).reduceLeft(_ + ", " + _) + "]"
    }
  }
}
def searchUserByName(user_name: String) = {
        (for (
            u <- Users if u.user_name.like(("%"+user_name+"%").bind)
        ) yield u.*)
        .list
        .map(User.tupled(_))
    }

    def toXml(users:List[User]) = {
        <users>
            { users.map(u => u.toXml) }
        </users>
    }

    def toJson(users:List[User]) = {
      "[" + users.map(u => u.toJson).reduceLeft(_ + ", " + _) + "]"
    }

And from the controller.

// -- http://localhost:9000/api/users/getUser/xml
// -- http://localhost:9000/api/users/getUser/json
def getUser(requestType:String) = {
  db withSession{
    val user = Users.byUserName("King.Kong")  
    if(requestType == "xml") {
      Xml(user.toXml)
    } else {
       user.toJson
    }
  }
}

//--- http://localhost:9000/api/users/searchuser/xml
//--- http://localhost:9000/api/users/searchuser/json
def searchUser(requestType:String) = {

  db withSession{
    val users = Users.searchUserByName("Doctor.Spoc")  
    if(requestType == "xml") {
      Xml(Users.toXml(users))
    } else {
        val jsonList = Users.toJson(users)
        Json(jsonList)
    }



  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文