I have a Kafka consumed record that will be parsed as JsValue with spray.json in scala, but I also have some data in the record's header, and I want to do:
Consume record with Alpakka Kafka library (done)
parse as json of type
JsValue:kafkaRecord.record.value().parseJson(also done)Append the record's header to that
JsValue(HERE IS THE MAIN CONCERN)Header = kafkaRecord.record.headers()Appending should include key[String]: value(header)
convert to pre-defined case class using
[JsValue].convertTo[<case class>]
Here is the consumed record for example:
{"id": 23, "features": "features_23"}
and want to append to it the Header to be as:
{"id": 23, "features": "features_23", "header_data":"Header_23"}
Then convert to case class:
case class recordOfKafka(id: Int, features: String, header_data: String)
Assuming some functions that get the string value of the record and header:
And the model with formatter:
You can parse record value and header in separate json objects, and then combine their fields together:
One thing to take care about is that, if you want to use
.asJsObjectyou must be sure that the records are json objects, like if you receive:It'll throw exceptions since this is an json array and cannot be converted to json object! You can also use try or pattern matching for conversion to JsObject to be safer.