Mozzer Mozzer - 1 month ago 21
Scala Question

How can i read and modify a json file in scala spark play

I want to read a JSON file and create a class/object that saved all label and value from every JSON's vector/record. Then I want to modify some values (or the JSON structure) and get this modified JSON file to Http request with play/spark/scala.

So how can I fill my class's variables with the json's values?

For example, I have this JSON file

[
{
"ser": 345,
"City": "New York",
"Gen": 1
},
{
"ser": 55,
"City": "New York",
"Gen": 2
},
{
"ser": 19,
"City": "New York",
"Gen": 3
}
]


My goal is create a class like this

class Book(ser:Integer, city:String, Gen:Integer)
{
//TODO
}


That takes every value of ser, city and gen, from the json for all the records in the file.
Than I want to modify the structure or values of the json, save and answer with the new file to a Http request.

Answer

Assuming you have this class

case class Book(ser: Int, city: String, gen: Int)

you can perform the JSON conversion using Play's JSON serialization/deserialization by implementing a formatter:

implicit val bookFormat: Format[Book] = {
  ((JsPath \ "ser").format[Int] and
    (JsPath \ "City").format[String] and
    (JsPath \ "Gen").format[Int]
    ) (Book.apply, unlift(Book.unapply))
}

// returns a sequence of Book objects
val books = Json.parse(bookJson).as[Seq[Book]]
// modify your books...
(...)
// convert back to Json
val json = Json.toJson(books)