V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
sadhen
V2EX  ›  程序员

用 Scala 在 V2EX 做抽奖活动

  •  
  •   sadhen ·
    darcy-shen · 2018-10-09 20:17:00 +08:00 · 557 次点击
    这是一个创建于 1997 天前的主题,其中的信息可能已经有所发展或是发生改变。

    准备活动,安装 Ammonite。

    brew install ammonite-repl
    

    或者按照 Ammonite 官网的命令行一键安装。用 brew 需要科学上网请在前面加 ALL_PROXY=socks5://localhost:1080

    抽奖代码很简单:

    import $ivy.`com.lihaoyi::requests:0.1.4`
    import $ivy.`org.json4s::json4s-jackson:3.5.2`
    import org.json4s.jackson.JsonMethods.parse
    import org.json4s._
    import org.json4s.JsonDSL._
    import scala.util.Random
    
    // 一些常量
    val url = "https://www.v2ex.com/api/replies/show.json?topic_id=493356"
    val numberOfWinners = 6
    
    // 从 V2EX 获取数据
    val source = requests.get(url)
    
    // 解析 JSON,获取所有参与抽奖的用户
    implicit val formats = DefaultFormats
    val json = parse(source.text)
    case class Profile(username: String, github: String)
    case class Member(member: Profile)
    val members = json.extract[List[Member]].map(_.member.username).distinct
    
    // 抽奖
    Random.shuffle(members).take(numberOfWinners)
    

    关于 JSON4S 的几点上手建议

    https://github.com/sadhen/12-technologies-in-2017/tree/master/05-json4s-in-15min

    比较笨,每次用都会查看自己写的这篇小文章。

    大家要抽取内容的时候,建议用case class,不要用\\\,反正我觉得后者看得我头疼,代码也不那么友好。

    一次性的话,怎么顺手怎么用,搭配 Ammonite,还是贼爽贼爽的。

    2 条回复    2018-10-09 22:17:39 +08:00
    sadhen
        1
    sadhen  
    OP
       2018-10-09 20:19:07 +08:00
    额 手贱发在问与答了
    yishenggudou
        2
    yishenggudou  
       2018-10-09 22:17:39 +08:00
    JSON4S 还是很难用 fastjson 好用很多
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3070 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 14:35 · PVG 22:35 · LAX 07:35 · JFK 10:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.