zoukankan      html  css  js  c++  java
  • 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. 添加隐式转换

  • 相关阅读:
    C
    B
    D
    I
    B
    E
    B
    L
    H
    bzoj3276磁力 两种要求下的最大值:分块or线段树+拓扑
  • 原文地址:https://www.cnblogs.com/wuning/p/11697410.html
Copyright © 2011-2022 走看看