Created
September 18, 2021 14:23
-
-
Save mikaello/61c05825baa73e920c3ef34417589cc0 to your computer and use it in GitHub Desktop.
Un URN JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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