Scala样例类转换为Json


1. 前言

业务上需求将SparkStreaming处理好的数据回传给广告平台

2. 代码

import org.json4s.{Formats, NoTypeHints}
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write

case class Student(id: Int, name: String, age: Int)

object Class2Json {
  
  // 需要添加隐式转换
  implicit val formats: AnyRef with Formats = Serialization.formats(NoTypeHints)

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

    val user1 = Student(1, name = "张三", 18)

    // 样例类转换为 Json字符串
    val str = write(user1)

    println(str)
  }
}

注意:
1. 引入json4s的jar包
2. 添加隐式转换


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM