Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Un URN JSON
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.databind.node.TextNode
private val typeMap = mutableMapOf<String, String>()
private fun parseReferences(jsonNode: JsonNode, path: String) {
val ITEMS = "items"
val ID = "id"
val PROPERTIES = "properties"
val ADDITIONAL_PROPERTIES = "additionalProperties"
val REF = "\$ref"
var currPath = path
if (jsonNode.has(ID)) {
typeMap.put(jsonNode.get(ID).asText(), currPath)
val properties: JsonNode = jsonNode.get(PROPERTIES)
val fields: Iterator<Map.Entry<String, JsonNode>> = properties.fields()
currPath += "/$PROPERTIES"
while (fields.hasNext()) {
val entry = fields.next()
parseReferences(entry.value, currPath + "/" + entry.key)
}
} else if (jsonNode.has(ITEMS)) {
val item: JsonNode = jsonNode.get(ITEMS)
parseReferences(item, "$currPath/$ITEMS")
} else if (jsonNode.has(REF)) {
val objectNode = jsonNode as ObjectNode
objectNode.set(REF, TextNode(typeMap.get(jsonNode.get(REF).asText())))
} else if (jsonNode.has(ADDITIONAL_PROPERTIES)) {
val additionalProperties: JsonNode = jsonNode.get(ADDITIONAL_PROPERTIES)
parseReferences(additionalProperties, "$currPath/$ADDITIONAL_PROPERTIES")
}
}
/**
* Remove URN from JSON, and replace with # type references
*/
fun parseReference(json: String): String {
val jaxbObjectMapper = ObjectMapper()
val root: JsonNode = jaxbObjectMapper.readTree(json)
parseReferences(root, "#")
return jaxbObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(root)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment