user461112
user461112

Reputation: 4151

Extracting certain fields from scala object <-> Json

I'm trying to extract certain fields from Scala object before converting to Json. Is there an easy way to do this.

It would also work if i could make a new Json with certain fields from a Json.

Upvotes: 0

Views: 634

Answers (2)

davidrpugh
davidrpugh

Reputation: 4563

Hard to say without more details. Suppose that you have the following Scala case class...

case class SomeObject(customerId: Long, addressId: Long, firstName: String, lastName: String, address: String)

...and that you wanted to extract the 'firstName', 'lastName', and address fields and then convert the object to Json. Using play-json you could define an implicit conversion on the companion object for the SomeObject class...

object SomeObject {

  implicit val someObjectWrites = new Writes[SomeObject] {
    def writes(object: SomeObject) = Json.obj(
      "firstName" -> object.firstName,
      "lastName" -> object.lastName,
      "address" -> object.address
    )
  }

}

Then you could just use the code as follows:

val obj = SomeObject(12345, 678910, "John", "Doe", "My Address")
val json = Json.toJson(obj)

Note that there are probably other JSON libraries, besides play-json, that support similar functionality.

Upvotes: 0

Sagan Pariyar
Sagan Pariyar

Reputation: 200

You can simply extract out the value of a Json and scala gives you the corresponding map. Example:

 var myJson = Json.obj(
          "customerId" -> "xyz",
          "addressId" -> "xyz",
          "firstName" -> "xyz",
          "lastName" -> "xyz",
          "address" -> "xyz"
      )

Suppose you have the Json of above type. To convert it into map simply do:

var mapFromJson = myJson.value

This gives you a map of type : scala.collection.immutable.HashMap$HashTrieMap

Upvotes: 3

Related Questions