Skip to content

Instantly share code, notes, and snippets.

@cjwebb
Created June 17, 2015 09:50
Show Gist options
  • Save cjwebb/7e444eb36ec92fb904fd to your computer and use it in GitHub Desktop.
Save cjwebb/7e444eb36ec92fb904fd to your computer and use it in GitHub Desktop.
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