All Downloads are FREE. Search and download functionalities are using the official Maven repository.

gsonpath.model.MandatoryFieldInfoFactory.kt Maven / Gradle / Ivy

Go to download

An annotation processor which generates Type Adapters for the Google Gson library

There is a newer version: 4.0.0
Show newest version
package gsonpath.model

class MandatoryFieldInfoFactory {

    /**
     * Keeps track of mandatory json field metadata.
     */
    class MandatoryFieldInfo(
            val indexVariableName: String,
            val gsonField: GsonField)

    /**
     * Add any mandatory field indexes as constants. This is done for code readability.
     * We will obtain the values using a depth-first recursion.
     */
    fun createMandatoryFieldsFromGsonObject(gsonObject: GsonObject): Map {
        return gsonObject.entries()
                .fold(emptyMap()) { map, (_, gsonModel) ->
                    when (gsonModel) {
                        is GsonField -> handleField(gsonModel, map)
                        is GsonObject -> map.plus(createMandatoryFieldsFromGsonObject(gsonModel))
                        is GsonArray -> handleArray(gsonModel, map)
                    }
                }
    }

    /**
     * For all required fields we add an index field so we can easily check whether the
     * value has been assigned after the json has been parsed.
     */
    private fun handleField(
            gsonModel: GsonField,
            map: Map): Map {

        return when {
            gsonModel.isRequired -> {
                val fieldName = gsonModel.fieldInfo.fieldName
                val mandatoryFieldIndexName = "MANDATORY_INDEX_" + fieldName.toUpperCase()

                // Keep track of the information for later use. Since this is a linked list, we keep track of insert order.
                map.plus(Pair(fieldName, MandatoryFieldInfo(mandatoryFieldIndexName, gsonModel)))
            }
            else -> map
        }
    }

    private fun handleArray(
            arrayModel: GsonArray,
            map: Map): Map {

        return arrayModel.entries()
                .fold(map) { arrayMap, (_, arrayGsonModel) ->
                    when (arrayGsonModel) {
                        is GsonField -> handleField(arrayGsonModel, arrayMap)
                        is GsonObject -> arrayMap.plus(createMandatoryFieldsFromGsonObject(arrayGsonModel))
                    }
                }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy