scala case class + BeanProperty+fastjson 快速实现类的序列化与反序列化

在实际的开发中,我们往往需要定义大量的类结构,来实现面向对象式的数据管理。考虑一种场景,这种场景下单个类管理的类成员变量有很多个,我们如何实现在少量代码编写的情况先实现一个类的序列化?

1. 在Java 中要实现一个类的序列化,需要 implements Serializable ,这个类需要是 OPJO 。那么在scala 中,我们知道 BeanProperty 会帮我们实现 get/set 方法,可以极大的缩减代码量

2. 序列化我们使用 alibaba 的fastjson

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
            <scope>compile</scope>
        </dependency>

 

1. 首先我们看下java 中如何实现:

package java_demo;

import java.io.Serializable;

public class Students implements Serializable {
    //姓名
    private String name;
    //年龄
    private String age;
    //住址
    private String address;

    public Students() {
    }

    public Students(String name, String age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    @Override
    public String toString() {
        return "Students{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
Students

使用fastjson 序列化:

package java_demo;

import com.alibaba.fastjson.JSONObject;

public class ToJson {
    public static void main(String[] args) {

        System.out.println("---------- Class Students --------");
        // object -> json
        Students s = new Students("wang","10","beijing");
        String objStr = JSONObject.toJSONString(s);
        System.out.println(objStr);

        // json -> object
        Students js = JSONObject.parseObject(objStr, Students.class);
        System.out.println(js);
    }
}

output:

---------- Class Students --------
{"address":"beijing","age":"10","name":"wang"}
Students{name='wang', age='10', address='beijing'}

 


2. 再来看下scala 中如何实现:

1. 手动实现 get/set:

package scala_demo

class Students {
  var name: String = _
  var age: String = _
  var address: String = _

  def this(name: String, age: String, address: String) {
    this() // 调用主构造函数
    this.name = name
    this.age = age
    this.address = address
  }

  def getName(): String = this.name
  def getAge(): String = this.age
  def getAddress(): String = this.address

  def setName(name: String) = this.name = name
  def setAge(age: String) = this.age = age
  def setAddress(address: String) = this.address = address
  override def toString: String = {
    this.getClass.getSimpleName + s"{name:'$name',age:'$age',address:'$address'}"
  }
}
Students

2. 使用BeanProperty实现

package scala_demo

import scala.beans.BeanProperty

class BeanStudents {
  @BeanProperty var name: String = _
  @BeanProperty var age: String = _
  @BeanProperty var address: String = _

  // 必须实现构造函数
  def this(name: String, age: String, address: String) {
    this()
    this.name = name
    this.age = age
    this.address = address
  }
}
BeanStudents

3. 使用case clase + BeanProperty实现

package scala_demo

import scala.beans.BeanProperty
case class CaseStudents (
@BeanProperty var name:String="",
@BeanProperty var age:String="",
@BeanProperty var address:String=""
)

查看编译后的class 文件信息: 

Compiled from "CaseStudents.scala"
public class scala_demo.CaseStudents implements scala.Product,scala.Serializable {
  private java.lang.String name;
  private java.lang.String age;
  private java.lang.String address;
  public static java.lang.String $lessinit$greater$default$3();
  public static java.lang.String $lessinit$greater$default$2();
  public static java.lang.String $lessinit$greater$default$1();
  public static scala.Option<scala.Tuple3<java.lang.String, java.lang.String, java.lang.String>> unapply(scala_demo.CaseStudents);
  public static java.lang.String apply$default$3();
  public static java.lang.String apply$default$2();
  public static java.lang.String apply$default$1();
  public static scala_demo.CaseStudents apply(java.lang.String, java.lang.String, java.lang.String);
  public static scala.Function1<scala.Tuple3<java.lang.String, java.lang.String, java.lang.String>, scala_demo.CaseStudents> tupled();
  public static scala.Function1<java.lang.String, scala.Function1<java.lang.String, scala.Function1<java.lang.String, scala_demo.CaseStudents>>> curried();
  public java.lang.String name();
  public void name_$eq(java.lang.String);
  public java.lang.String age();
  public void age_$eq(java.lang.String);
  public java.lang.String address();
  public void address_$eq(java.lang.String);
  public scala_demo.CaseStudents copy(java.lang.String, java.lang.String, java.lang.String);
  public java.lang.String copy$default$1();
  public java.lang.String copy$default$2();
  public java.lang.String copy$default$3();
  public java.lang.String getAddress();
  public java.lang.String getAge();
  public java.lang.String getName();
  public void setAddress(java.lang.String);
  public void setAge(java.lang.String);
  public void setName(java.lang.String);
  public java.lang.String productPrefix();
  public int productArity();
  public java.lang.Object productElement(int);
  public scala.collection.Iterator<java.lang.Object> productIterator();
  public boolean canEqual(java.lang.Object);
  public int hashCode();
  public java.lang.String toString();
  public boolean equals(java.lang.Object);
  public scala_demo.CaseStudents(java.lang.String, java.lang.String, java.lang.String);
}
CaseStudents.class

 

序列化:

package scala_demo

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializerFeature

object ToJson {
  def main(args: Array[String]): Unit = {
    println("--------- Class: Students ---------")
    // object -> json
    val students:Students = new Students("Zhao","10","BeiJing")
    val objStr = JSON.toJSONString(students, SerializerFeature.QuoteFieldNames)
    println(objStr)

    val js = JSON.parseObject(objStr,new Students().getClass)
    println(js)

    println("--------- Bean Class: Students ---------")
    val beanStudents = new BeanStudents("Sun","20","HangZhou")
    val objBeanStr = JSON.toJSONString(beanStudents,SerializerFeature.QuoteFieldNames)
    println(objBeanStr)

    val beanJs = JSON.parseObject(objBeanStr,new BeanStudents().getClass)
    println(beanJs)
    println(beanJs.name,beanJs.age,beanJs.address)

    println("--------- Case Class: Students ---------")
    val caseStudents = CaseStudents("Xian","10","ShangHai")
    val objCaseStr = JSON.toJSONString(caseStudents ,SerializerFeature.QuoteFieldNames)
    println(objCaseStr)

    val caseJs = JSON.parseObject(objCaseStr,CaseStudents().getClass)
    println(caseJs)
  }
}

output:

--------- Class: Students ---------
{"address":"BeiJing","age":"10","name":"Zhao"}
Students{name:'Zhao',age:'10',address:'BeiJing'}
--------- Bean Class: Students ---------
{"address":"HangZhou","age":"20","name":"Sun"}
scala_demo.BeanStudents@66480dd7
(Sun,20,HangZhou)
--------- Case Class: Students ---------
{"address":"ShangHai","age":"10","name":"Xian"}
CaseStudents(Xian,10,ShangHai)

 

可以看到第3中方式可以极大程度的缩减代码量并在此基础上实现序列化

posted @ 2020-09-27 09:11  feiquan  阅读(1966)  评论(0编辑  收藏  举报
如果是此文是转载文章,本人会附上转载链接,此篇文章的版权归原创作者所属,如果侵权请与我联系,我会删除此文。

若没有标明转载链接,此篇文章属于本人的原创文章,其版权所属:
作者:feiquan
出处:http://www.cnblogs.com/feiquan/
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
大家写文都不容易,请尊重劳动成果~ 这里谢谢大家啦(*/ω\*)