pwall567 / json-kotlin-schema

Kotlin implementation of JSON Schema (Draft 07)
MIT License
90 stars 13 forks source link

Load schema from stream or string #1

Closed dellisd closed 3 years ago

dellisd commented 3 years ago

Currently it looks like it's only possible to load the schema by providing a File or a string with the name of a file which limits certain use cases of this library.

For instance, if I wanted to load a schema from my project's resources:

val schema: InputStream = javaClass.classLoader.getResourceAsStream("schema.json")

there's no way to initialize the schema with this, other than writing the resource to a file first which isn't ideal.

JH108 commented 3 years ago

It looks like #2 will resolve the part of this issue requesting to parse a String but in the meantime, I was able to do this by defining a simple method and then using it in my class that needed to parse a JSONSchema from a String. In my case, the schemas are coming from an API so I don't have the option to use a File.

Credit: @poom-sci for the idea based on his PR.

Simple example of my solution

import net.pwall.json.JSON
import net.pwall.json.pointer.JSONPointer
import net.pwall.json.schema.JSONSchema

class UseJsonSchema {
    var jsonSchema: JSONSchema

    private fun parseJson(data: String): JSONSchema {
        val json = JSON.parse(data)
        val pointer = JSONPointer.root

        return JSONSchema.parser.parseSchema(json, pointer, null)
    }

    constructor(jsonSchema: String) {
        this.jsonSchema = parseJson(jsonSchema)
    }
  // Other code that does additional work with the schema
}
pwall567 commented 3 years ago

I apologise for not having noticed this sooner. You're right - it was an oversight not to include a function to load a schema from a string.

I have merged the PR from @poom-sci and deployed it as version 0.22. I hope this meets that requirement.

pwall567 commented 3 years ago

I believe this problem is resolved so I'm closing the issue. Please feel free to raise another issue there any further problems.