Play中JSON序列化

根据经验Json处理是比较简单的,但是Play和akka-http的序列化让我烦恼了不少时间,所以我从自己的角度记录一下Play的JSON处理,代码也都是从官方文档复制后重新整理的,下面是参考的官方文档下有几篇JSON的文章

Working with Json

  1. JSON basics
  2. JSON with HTTP
  3. JSON Reads/Writes/Format Combinators
  4. JSON automated mapping
  5. JSON Transformers

实体序列化例子

1.本例中使用的实体类

package serialize

case class Location(lat: Double, long: Double)
case class Resident(name: String, age: Int, role: Option[String])
case class Place(name: String, location: Location, residents: Seq[Resident])

2.序列化例子

import play.api.libs.json._
import play.api.libs.functional.syntax._
import serialize.{Location, Place, Resident}

object PlayJsonTest{

  def main(args:Array[String]):Unit={

    implicit val locationReads = Json.reads[Location]
    implicit val residentReads = Json.reads[Resident]
    implicit val placeReads = Json.reads[Place]

    val json: JsValue = Json.parse("""
                  {
                    "name" : "Watership Down",
                    "location" : {
                      "lat" : 51.235685,
                      "long" : -1.309197
                    },
                    "residents" : [ {
                      "name" : "Fiver",
                      "age" : 4,
                      "role" : null
                    }, {
                      "name" : "Bigwig",
                      "age" : 6,
                      "role" : "Owsla"
                    } ]
                  }
                  """)

    val result: JsResult[Place] = Json.fromJson[Place](json)

    result match {
      case JsSuccess(r: Place, path: JsPath) => println("Name: " + r.name)
      case e: JsError => println("Errors: " + JsError.toJson(e).toString())
    }
  }
}

3.解释

一般的json序列化比较简单,有一个类似JsonManager的管理类,提供serialize(object obj)与deserialize<T>(string json)这样方法,一般不需要开发者做太多的工作,比较简单,也是基于这种认识,所以对play的json处理方式就会困惑。

原因是scala和akka系列声称自己是可伸缩的框架,面向大数据领域,他认为传统的方式是比较重的oo方式,而大数据的处理主要是批量处理数据,所以可能只是对批量数据的个别字段做简单的运算即可,不需要沉重的OOM,看他原文的描述:

Are we doomed to convert JSON to OO?

For a few years now, in almost all web frameworks (except recent JavaScript server side stuff maybe in which JSON is the default data structure), we have been used to get JSON from network and convert JSON (or even POST/GET data) into OO structures such as classes (or case classes in Scala). Why?

  • For a good reason : OO structures are “language-native” and allows manipulating data with respect to your business logic in a seamless way while ensuring isolation of business logic from web layers.
  • For a more questionable reason : ORM frameworks talk to DB only with OO structures and we have (kind of) convinced ourselves that it was impossible to do else… with the well-known good & bad features of ORMs… (not here to criticize those stuff)

Is OO conversion really the default use case?

In many cases, you don’t really need to perform any real business logic with data but validating/transforming before storing or after extracting. Let’s take the CRUD case:

  • You just get the data from the network, validate them a bit and insert/update into DB.
  • In the other way, you just retrieve data from DB and send them outside.

So, generally, for CRUD ops, you convert JSON into a OO structure just because the frameworks are only able to speak OO.

I don’t say or pretend you shouldn’t use JSON to OO conversion but maybe this is not the most common case and we should keep conversion to OO only when we have real business logic to fulfill.

4.总结

先要知道play的json的关注点,以及他的思维方式,对于这种思维方式的好与坏,其实也无所谓。

原文地址:https://www.cnblogs.com/Netsharp/p/9938917.html

时间: 2024-11-05 21:59:31

Play中JSON序列化的相关文章

C#中JSON序列化和反序列化

json序列化和反序列化帮助类: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.IO; using System.Text.RegularExpressions; using System.We

Asp.Net Core中Json序列化处理整理

一.Asp.Net Core中的Json序列化处理使用的是Newtonsoft.Json,更多参考:C# Newtonsoft.Json JsonSerializerSettings配置序列化操作,C# Json序列化工具--Newtonsoft.Json简介和使用 1.Newtonsoft.Json仅 依赖.Net Standard所以支持.Net Framework也支持.Net Core 2.更多说明 /* * 1.在Core Mvc中JsonResult 默认支持Get请求 * 2.使用

PHP中json序列化后中文的编码显示问题

在接口返回数据中,我们经常会返回json或者xml格式,php的json序列化函数json_encode非常好用,但是默认会把中文编码为ASCII码(注意,很多人认为这是乱码,其实不是),尤其在调试接口时,看到一大串的ASCII码,一脸懵逼,不知是对是错: 代码: <?php class A { public $num; public $name; function __construct($_num,$_name) { $this->num=$_num; $this->name=$_n

EF中Json序列化对象时检测到循环引用的解决办法

第一种方法:使用Newtonsoft.Json中的方法注释,在Json序列化的时候忽略导航属性 例:using Newtonsoft.Json; public class Users { public int Id { get; set; } public string LoginId { get; set; } public string LoginPwd { get; set; } [JsonIgnore] public virtual ICollection Roles { get; se

EntityFramework中Json序列化的循环引用问题解决--Newtonsoft.Json

1.在使用EF时,由于数据库主外键关联,将对象进行Json序列化时会遇到循环引用的问题 //EF 中由于数据库主外键关联,对象的序列化经常出现循环引用问题 //使用.Net 自带的序列化工具,序列化出现循环引用问题 List<student> list = _Context.students.ToList(); JavaScriptSerializer ser = new JavaScriptSerializer(); string str = ser.Serialize(list); Con

javaScript中JSON序列化器/解析器

在JSON库中有一个全局的JSON对象, 包括两2个方法:序列化器即parse() 和 解析器stringify() 下面就介绍一个这两个方法的使用: 1.parse()用于将JSON字符串解析为对象或数组 var jsonText = '{"userName":"zhangsan","password":"123456"}';//注:  每个属性名和值都要用双引号, 单引号写在外面, 否则会出现异常. var changeJ

.NET中Json序列化反序列化操作辅助类——基于Json.NET

/// <summary> /// Json操作辅助类 /// </summary> public static class JsonHelper { private static JsonSerializerSettings _jsonSettings; static JsonHelper() { IsoDateTimeConverter datetimeConverter = new IsoDateTimeConverter(); datetimeConverter.DateT

C#中 Json 序列化和反序列化的函数

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); //执行序列化 string r1 = jsonSerializer.Serialize(personnel); //执行反序列化 Personnel _Personnel = jsonSerializer.Deserialize<Personnel>(r1);

ASP.NET 中JSON 的序列化和反序列化

JSON是专门为浏览器中的网页上运行的JavaScript代码而设计的一种数据格式.在网站应用中使用JSON的场景越来越多,本文介绍ASP.NET中JSON的序列化和反序列化,主要对JSON的简单介绍,ASP.NET如何序列化和反序列化的处理,在序列化和反序列化对日期时间.集合.字典的处理. 一.JSON简介: JSON(JavaScript Object Notation,JavaScript对象表示法)是一种轻量级的数据交换格式. JSON是"名值对"的集合.结构由大括号''{}'