vert-x / mod-mysql-postgresql

Vert.x 2.x is deprecated - use instead
http://vertx.io/docs/vertx-mysql-postgresql-client/java/
Apache License 2.0
49 stars 17 forks source link

How to deserialize the returned row to a java object? #25

Closed anidotnet closed 10 years ago

anidotnet commented 10 years ago

As the datatype of returned row is json array, how to deserialize easily the returned row to a java object? May be it is the scope of an ORM, but any guidelines would be helpful.

Narigo commented 10 years ago

This is out of scope of this module as it's not only for Java users. :)

Maybe what we used in Scala will give you an idea what you can do:

  /**
   * Maps the results array from the mod-mysql-postgresql with the fields array like:
   * [{field1: val1, field2:val2}, {field1: val1, field2: val2}]
   *
   * With this you can easily access the results of a query with the name of the columns instead of indices
   *
   * @param json The Json which is returned by the mod-mysql-postgresql module
   * @return A JsonArray which has the fieldnames and values mapped together
   */
  private def mapFieldsOnResults(json: JsonObject): JsonObject = {
    import scala.collection.JavaConverters._

    Option(json.getArray("fields")) match {
      case Some(jarr) => {
        val fields = jarr.asScala.zipWithIndex
        val results = json.getArray("results")

        val x = for {
          entry <- results.asScala.map(_.asInstanceOf[JsonArray])
        } yield {
          Json.obj(fields.map { case (fieldName, idx) => (fieldName.toString, entry.get[Any](idx)) }.toSeq: _*)
        }

        json.putArray("mappedFields", Json.arr(x.toSeq: _*))
      }
      case None => json
    }

  }

Put the message.body from the event bus in there and you get a JsonObject with fields->value back. Maybe Jackson or something similar can help you create a Java object out of this?

Otherwise, why not just have a Factory for the Java object you want that takes the JsonArray from the result here?

anidotnet commented 10 years ago

Thanks for the input. Though I don't know scala at all, but I got the idea that you are iterating both arrays - fields & result and creating the jsonobject array. If really this is what the code snippet is doing then it can be done in Java as well.