Mongodb Document to Scala case class

前端 未结 2 1645

I am using MongoDB scala driver. I have a problem with fetching record from MongoDB. Following is my MongoDB initialization

private val client: MongoClient          


        
相关标签:
2条回答
  • 2021-01-14 21:42

    You could use a JSON library.

    In play-json

    case class WorkOrder (
      id: String,
      workOrderId: String,
      thingId: String,
      alertId: String,
      description: String,
      lastViewedDate: Date,
      suggestedMaintenanceDate: Date,
      startDate: Date
    )
    
    object WorkOrder {
      implicit lazy val fmt = Json.format[WorkOrder]
    }
    
    def documentToWorkOrder(doc: Document): WorkOrder = {
      Json.parse(user.toJson().toString).validate[WorkOrder] match {
        case JsSuccess(_, workOrderObj) => workOrderObj
        case JsError(throwable)  => throw throwable
      }
    }
    
    //then in your code
    MongoFactory.WorkOrdercollection.find(query).subscribe(
     (user: Document) => documentToWorkOrder(user),
     (error: Throwable) => println(s"Query failed: ${error.getMessage}"),
     () => println("Done")
    )
    
    0 讨论(0)
  • 2021-01-14 21:43

    You need to provide a custom codec for $date field. The following shows how it is done in play-json but the concept is similar in other JSON libraries:

    object WorkOrder {
      implicit val dateRead: Reads[Date] =
        (__ \ "$date").read[Long].map(date => new Date(date))
    
      implicit val dateWrite: Writes[Date] = new Writes[Date] {
        def writes(date: Date): JsValue = Json.obj("$date" -> date.getTime)
      }
    
      implicit val codec = Json.format[WorkOrder]
    }
    
    0 讨论(0)
提交回复
热议问题