• Scala对象数据封装成json并输出


    背景:

    Sparkstreaming计算完成的数据封装成对象后需要转换成json并输出到Redis

    问题:

    1、scala对象无法序列化

    2、sclaa对象序列化后为空

    解决方案:

    1、样例类必须加上注解@BeanProperty,这样scala的类中的属性就有了get,set方法

    case class ItemRelevant(
                             @BeanProperty anchorId: Long = 0L, //主播id
                             @BeanProperty liveId: Long, //直播id
                             @BeanProperty itemId: Long, //商品id
                             @BeanProperty itemName: String, //商品名字
                             @BeanProperty itemPrice: Double, //商品直播价格
                             @BeanProperty shopName: String, //店铺名字
                             @BeanProperty cateName: String, //商品类目
                             @BeanProperty upTime: String, //商品上架时间
                             @BeanProperty image: String, //商品图片
                             @BeanProperty var saleNum: Long = 0L, //商品实时销量
                             @BeanProperty var salesVolume: Double = 0.0, //商品实时销售额
                             //机器本地时间 2020-10-09 使用此样例类,此参数不需要传入
                             @BeanProperty var dayString: String = null, //年月日
                             //机器本地时间 11:20:30 使用此样例类,此参数不需要传入
                             @BeanProperty var hmString: String = null) { //时分秒
      val date = new Date(System.currentTimeMillis())
      dayString = new SimpleDateFormat("yyyy-MM-dd").format(date)
      hmString = new SimpleDateFormat("HH:mm:ss").format(date)
    }

    2、本次采用的是fastjosn的方式将scala的对象转换成json并输出,值得注意的是,使用scala代码需要指定JSON.toJSONString的第二的参数,否则,对象的属性的值为空,第二个参数部分列举如下:

    名称 含义
    QuoteFieldNames 输出key时是否使用双引号,默认为true
    UseSingleQuotes 使用单引号而不是双引号,默认为false
    WriteMapNullValue 是否输出值为null的字段,默认为false
    WriteEnumUsingToString Enum输出name()或者original,默认为false
    SortField 按字段名称排序后输出。默认为false
    WriteTabAsSpecial 把 做转义输出,默认为false
    PrettyForma 结果是否格式化,默认为false
    WriteClassName 序列化时写入类型信息,默认为false。反序列化是需用到

    3、此时有一个对象x是ItemRelevant类,那么x转换成json格式的代码如下:

    val y = JSON.toJSONString(x, SerializerFeature.PrettyFormat)
  • 相关阅读:
    AD设置PCB等比例打印
    leetcode------Word Search
    leetcode------Subsets II
    leetcode------Subsets
    leetcode------Palindrome Partitioning
    leetcode------Combinations
    leetcode------Binary Tree Zigzag Level Order Traversal
    leetcode------Populating Next Right Pointers in Each Node II
    leetcode------Populating Next Right Pointers in Each Node
    leetcode------Remove Duplicates from Sorted Array II
  • 原文地址:https://www.cnblogs.com/atBruce/p/13982614.html
Copyright © 2020-2023  润新知