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. 添加隐式转换

猜你喜欢

转载自www.cnblogs.com/wuning/p/11697410.html
今日推荐