Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Basic JSON Schema validation with Scala and https://github.com/fge/json-schema-validator
import com.github.fge.jsonschema.core.report.ProcessingMessage
import scala.collection.JavaConversions._
import com.fasterxml.jackson.databind.JsonNode
import com.github.fge.jsonschema.main.JsonSchemaFactory
import org.json4s._
import org.json4s.jackson.JsonMethods._
object Main extends App {
val json = """{"hello":"world"}"""
val jsonSchema = """{
| "title":"hello world schema",
| "type":"object",
| "properties":{
| "hello": {
| "type": "string"
| }
| },
| "required":["hello"]
|}""".stripMargin
val schema: JsonNode = asJsonNode(parse(jsonSchema))
val instance: JsonNode = asJsonNode(parse(json))
val validator = JsonSchemaFactory.byDefault().getValidator
val processingReport = validator.validate(schema, instance)
if (processingReport.isSuccess) {
println("JSON Schema validation was successful")
} else {
processingReport.foreach { message: ProcessingMessage =>
println(message.asJson())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment