其他分享
首页 > 其他分享> > Scala中使用 Jackson API 进行JSON序列化和反序列化

Scala中使用 Jackson API 进行JSON序列化和反序列化

作者:互联网

1.  什么是 Json 序列化 和 反序列化

序列化 => 将 Java对象 转换成 json字符串
反序列化 => 将 json字符串 转换成 Java对象

2. 依赖包 说明

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.4</version>
</dependency>
依赖包说明:
    # 提供注解支持
    Maven: com.fasterxml.jackson.core:jackson-annotations:2.7.0
    # 核心功能支持
    Maven: com.fasterxml.jackson.core:jackson-core:2.10.1
    Maven: com.fasterxml.jackson.core:jackson-databind:2.7.4

3. ObjectMapper

    功能:
        ObjectMapper 提供了 读写Json的功能
    读:
        public <T> T readValue(String content, Class<T> valueType)
            将 字符串content 反序列化 成 Class<T>类型的对象
        
    写(可以把JSON字符串保存File、OutputStream等不同的介质中):
        public void writeValue(File resultFile, Object value)
            将 Objec转成 json字符串,并保存到 指定 File 内
            
        public void writeValue(OutputStream out, Object value)
            将 Objec转成 json字符串,并保存到 指定 OutputStream 内(使用 UTF8 编码)
            
        public byte[] writeValueAsBytes(Object value)
            将 Objec转成 json字符串,并把结果输出成 字节数组
            
        public String writeValueAsString(Object value)
             将 Objec转成 json字符串,并把结果输出成 字符串

4. Json 注解

    @JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性

    @JsonFormat 此注解用于属性上,作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")。
        示例: @JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")
        
    @JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称
        示例: @JsonProperty("AliasName")

5. Bean对象 => Json 字符串 (Json 序列化) 

// TODO 用来转换的 Bean
case class UserBean(@BeanProperty name: String
                    , @BeanProperty age: Int
                    , @BeanProperty birthday: Date
                    , @BeanProperty email: String)

// TODO Bean对象 => Json 字符串 (Json 序列化)
object Bean2Json extends App {

  val user: UserBean = UserBean("张飞", 21, new Date(), "hao123@163.com")

  val mapper: ObjectMapper = new ObjectMapper()

  // user 对象 转 json字符串
  val beanJson: String = mapper.writeValueAsString(user)

  println(beanJson)
  // {"name":"张飞","age":21,"birthday":1660115099317,"email":"hao123@163.com"}

  // scala 集合 转 json字符串
  val list: Array[UserBean] = Array(
    UserBean("刘备", 21, new Date(), "hao123@163.com"),
    UserBean("关羽", 22, new Date(), "hao456@163.com"),
    UserBean("张飞", 23, new Date(), "hao789@163.com")
  )

  private val listJson: String = mapper.writeValueAsString(list)

  println(listJson)
  // [{"name":"刘备","age":21,"birthday":1660115099712,"email":"hao123@163.com"},{"name":"关羽","age":22,"birthday":1660115099712,"email":"hao456@163.com"},{"name":"张飞","age":23,"birthday":1660115099712,"email":"hao789@163.com"}]
}

6. Json 字符串 => Bean对象 (Json 反序列化)

// TODO 由于 利用反射 对json串反序列化,所有必须有 空参构造 + get、set方法
class UserBean1() {
  @BeanProperty var name: String = _
  @BeanProperty var age: Int = _
  @BeanProperty var birthday: Date = _
  @BeanProperty var email: String = _

  override def toString = s"UserBean1($name, $age, $birthday, $email)"
}

// TODO Json 字符串 => Bean对象 (Json 反序列化)
object Json2Bean extends App {
  val jsonBean: String =
    """
      |{"name":"张飞","age":21,"birthday":1660115099317,"email":"hao123@163.com"}
    """.stripMargin

  val jsonArray: String =
    """
      |[{"name":"刘备","age":21,"birthday":1660115099712,"email":"hao123@163.com"},{"name":"关羽","age":22,"birthday":1660115099712,"email":"hao456@163.com"},{"name":"张飞","age":23,"birthday":1660115099712,"email":"hao789@163.com"}]
    """.stripMargin

  val mapper: ObjectMapper = new ObjectMapper()

  // json 转 bean 对象
  private val bean: UserBean1 = mapper.readValue(jsonBean, classOf[UserBean1])

  // json 数组 转 bean 对象数组
  private val array: Array[UserBean1] = mapper.readValue(jsonArray, classOf[Array[UserBean1]])

  array.foreach(println(_))

  println(bean)
}

7. 使用注解

class UserBean2() {
  @JsonIgnore //进行JSON操作时忽略该属性
  @BeanProperty var name: String = _

  @BeanProperty var age: Int = _

  @JsonFormat(pattern = "yyyy-MM-dd") // 格式化日期属性
  @BeanProperty var birthday: Date = _

  @JsonProperty("mail_Alias")
  @BeanProperty var email: String = _

  override def toString = s"UserBean2($name, $age, $birthday, $email)"
}

// TODO 使用注解
object Bean2Json_Anno extends App {

  val user: UserBean2 = new UserBean2()

  user.setAge(21)
  user.setName("张飞")
  user.setBirthday(new Date())
  user.setEmail("hao123@163.com")

  val mapper: ObjectMapper = new ObjectMapper()

  // user 对象 转 json字符串
  val beanJson: String = mapper.writeValueAsString(user)

  println(beanJson)
  // {"age":21,"birthday":"2022-08-10","mail_Alias":"hao123@163.com"}

}

 

标签:Jackson,val,Scala,age,birthday,序列化,com,163
来源: https://www.cnblogs.com/bajiaotai/p/16573210.html