scala - updating Json object -


i have json object need update. original object list looks this:

[   {     "firstname":"jane",     "lastname":"smith"   },   {     "firstname":"jack",     "lastname":"brown"   } ] 

for each element in list, have field, "age", needs added @ run-time, result should following:

[   {     "firstname":"jane",     "lastname":"smith",     "age": "21"   },   {     "firstname":"jack",     "lastname":"brown",     "age": "34"   } ] 

any suggestions how result still json?

thanks.

i recommended deserializing json array receive list of case classes, having function fill in missing attributes based on current attributes of case class, , serializing them json , serving response.

let's make person case class fields missing option:

import play.api.libs.json.json  case class person(firstname: string, lastname: string, age: option[int])  object person {     implicit val format: format[person] = json.format[person]      def addage(person: person): person = {         val age = ... // determine age         person.copy(age = some(age))     } } 

within companion object person i've defined json serializer/deserializer using format macro, , stub function find person's age copy person , return it.

deep within web service call might have this:

val jsarray = ... // jsvalue somewhere  jsarray.validate[list[person]].fold(     // handle case invalid incoming json     error => internalservererror("received invalid json response remote service."),     // handle deserialized array of list[person]     people => {         ok(             // serialize json, requires implicit `format` defined earlier.             json.tojson(                 // map each person themselves, adding age                 people.map(person => person.addage(person))             )         )     } ) 

this method safer, otherwise you'll have extract values array 1 one , concatenate objects, awkward. allow handle errors when json receive missing fields you're expecting.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -