2016-04-30 78 views
0

我想从S3存储桶合并两个JSON文件。第一个文件很好,但不是第二个文件。Scala:使用AmazonS3Client合并两个JSON文件getObject期货

val eventLogJsonFuture = Future(new AmazonS3Client(credentials)) 
    .map(_.getObject(logBucket, logDirectory + "/" + id + "/event_log.json")) 
    .map(_.getObjectContent) 
    .map(Source.fromInputStream(_)) 
    .map(_.mkString) 
    .map(Json.parse) map { archiveEvents => 

    Json.toJson(Json.obj("success" -> true, "data" -> archiveEvents)) 

    } recover { 
    case NonFatal(error) => 
     Json.obj("success" -> false, "errorCode" -> "archive_does_not_exist", "message" -> error.getMessage) 
    } 


val infoJsonFuture = Future(new AmazonS3Client(credentials)) 
    .map(_.getObject(logBucket, logDirectory + "/" + id + "/info.json")) 
    .map(_.getObjectContent) 
    .map(Source.fromInputStream(_)) 
    .map(_.mkString) 
    .map(Json.parse) map { archiveInfo => 

    Json.toJson(Json.obj("success" -> true, "data" -> archiveInfo)) 

} recover { 
    case NonFatal(error) => 
    Json.obj("success" -> false, "errorCode" -> "archive_does_not_exist", "message" -> error.getMessage) 
} 

val combinedJson = for { 
    eventLogJson <- eventLogJsonFuture 
    infoJson <- infoJsonFuture 
} 
yield { 
    Json.obj("info" -> infoJson, "events" -> eventLogJson) 
} 

这是JSON的结果看起来像......

this is the json result

有没有写这个的另一个(更好?)的方式?

+0

有什么问题你现在怎么做呢?看起来优雅。 –

+0

问题是,当文件确实存在于S3上时,infoJsonFuture正在抛出非致命错误...“输入长度= 1”。是否可能是AmazonS3Client可能无法在两个单独的线程上异步运行? –

+0

如果您等待来自不同来源的JSON的3个部分? “ – 2016-05-20 14:12:41

回答

0

如果您等待来自不同来源的JSON的3个部分?

我可以推荐与case class DTO

简单示例解决方案:

val firstJson = Future { 
     //case class json1(...) 
    } 

    val secondJson = Future { 
    //case class json2(...) 
     ... 
    } 

    val finalFson = for { 
     f <- first 
     s <- second 
    } yield (f, s) 

finalJson onComplete { 
     case Success(jsons) => { 
     //merge json here 
     jsons._1 + jsons._2 ... 

     }