Skip to content

Commit

Permalink
Support nullable array elements
Browse files Browse the repository at this point in the history
Also fix nullable property detection
  • Loading branch information
ark-1 committed Jul 14, 2024
1 parent d6abe59 commit 2ed9370
Show file tree
Hide file tree
Showing 13 changed files with 130 additions and 72 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ class KotlinListClassCodeBuilder : ICodeBuilder<ListClass> {

override fun getCode(clazz: ListClass): String {
clazz.run {
val elementType = if (nullableElements) generic.name + "?" else generic.name
return if (generic.modifiable.not()) {
getOnlyCurrentCode()
} else {
"""
class $name : ArrayList<${generic.name}>(){
class $name : ArrayList<$elementType>(){
${referencedClasses.filter { it.modifiable }.joinToString("\n\n") { it.getCode().prependIndent(" $indent") }}
}
""".trimIndent()
Expand All @@ -26,8 +27,9 @@ ${referencedClasses.filter { it.modifiable }.joinToString("\n\n") { it.getCode()

override fun getOnlyCurrentCode(clazz: ListClass): String {
clazz.run {
val elementType = if (nullableElements) generic.name + "?" else generic.name
return """
class $name : ArrayList<${generic.name}>()
class $name : ArrayList<$elementType>()
""".trimIndent()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import wu.seal.jsontokotlin.utils.LogUtil
* Created by Seal.Wu on 2019-11-23
* present a list class type like List<Any>
*/
data class GenericListClass(override val generic: KotlinClass) : UnModifiableGenericClass() {
data class GenericListClass(override val generic: KotlinClass, val nullableElements: Boolean) : UnModifiableGenericClass() {
override val name: String
get() = "List<${generic.name}>"
get() = if (nullableElements) "List<${generic.name}?>" else "List<${generic.name}>"

override val hasGeneric: Boolean = true

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import wu.seal.jsontokotlin.model.builder.*
data class ListClass(
override val name: String,
override val generic: KotlinClass,
val nullableElements: Boolean,
override val referencedClasses: List<KotlinClass> = listOf(generic),
override val modifiable: Boolean = true,
override val codeBuilder: KotlinListClassCodeBuilder = KotlinListClassCodeBuilder.DEFAULT
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class DataClassGeneratorByJSONSchema(private val rootClassName: String, private
): Property {
val (jsonClassName, realDef) = getRealDefinition(jsonProp)
val typeClass = resolveTypeClass(realDef.typeString, jsonClassName, realDef, propertyName)
val value = if (isRequired || !jsonProp.isTypeNullable) getDefaultValue(typeClass.name) else null
val value = if (isRequired || !realDef.isTypeNullable) getDefaultValue(typeClass.name) else null
return Property(
originName = propertyName,
originJsonValue = value,
Expand Down Expand Up @@ -86,7 +86,10 @@ class DataClassGeneratorByJSONSchema(private val rootClassName: String, private
propertyName,
false
)
GenericListClass(generic = innerProperty.typeObject)
GenericListClass(
generic = innerProperty.typeObject,
nullableElements = innerProperty.originJsonValue == null,
)
}
checkEnum && realDef.enum != null -> resolveEnumClass(realDef, simpleName)
checkSealed && realDef.anyOf != null -> resolveSealedClass(realDef, simpleName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package wu.seal.jsontokotlin.utils.classgenerator

import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonNull
import com.google.gson.JsonObject
import wu.seal.jsontokotlin.model.classscodestruct.GenericListClass
import wu.seal.jsontokotlin.model.classscodestruct.KotlinClass
import wu.seal.jsontokotlin.utils.*
Expand All @@ -15,20 +13,21 @@ import wu.seal.jsontokotlin.utils.*
class GenericListClassGeneratorByJSONArray(private val jsonKey: String, jsonArrayString: String) {

private val tag = "ListClassGeneratorByJSONArray"
private val jsonArray: JsonArray = Gson().fromJson(jsonArrayString, JsonArray::class.java)
private val jsonArray: JsonArray = readJsonArray(jsonArrayString)
private val jsonArrayExcludeNull = jsonArray.filterOutNullElement()
private val hasNulls get() = jsonArray.size() != jsonArrayExcludeNull.size()


fun generate(): GenericListClass {

when {
jsonArray.size() == 0 -> {
LogUtil.i("$tag jsonArray size is 0, return GenericListClass with generic type ANY")
return GenericListClass(generic = KotlinClass.ANY)
return GenericListClass(generic = KotlinClass.ANY, nullableElements = true)
}
jsonArray.allItemAreNullElement() -> {
LogUtil.i("$tag jsonArray allItemAreNullElement, return GenericListClass with generic type ${KotlinClass.ANY.name}")
return GenericListClass(generic = KotlinClass.ANY)
return GenericListClass(generic = KotlinClass.ANY, nullableElements = true)
}
jsonArrayExcludeNull.allElementAreSamePrimitiveType() -> {
// if all elements are numbers, we need to select the larger scope of Kotlin types among the elements
Expand All @@ -37,24 +36,24 @@ class GenericListClassGeneratorByJSONArray(private val jsonKey: String, jsonArra
val p = jsonArrayExcludeNull[0].asJsonPrimitive;
val elementKotlinClass = if(p.isNumber) getKotlinNumberClass(jsonArrayExcludeNull) else p.toKotlinClass()
LogUtil.i("$tag jsonArray allElementAreSamePrimitiveType, return GenericListClass with generic type ${elementKotlinClass.name}")
return GenericListClass(generic = elementKotlinClass)
return GenericListClass(generic = elementKotlinClass, nullableElements = hasNulls)
}
jsonArrayExcludeNull.allItemAreObjectElement() -> {
val fatJsonObject = jsonArrayExcludeNull.getFatJsonObject()
val itemObjClassName = getRecommendItemName(jsonKey)
val dataClassFromJsonObj = DataClassGeneratorByJSONObject(itemObjClassName, fatJsonObject).generate()
LogUtil.i("$tag jsonArray allItemAreObjectElement, return GenericListClass with generic type ${dataClassFromJsonObj.name}")
return GenericListClass(generic = dataClassFromJsonObj)
return GenericListClass(generic = dataClassFromJsonObj, nullableElements = hasNulls)
}
jsonArrayExcludeNull.allItemAreArrayElement() -> {
val fatJsonArray = jsonArrayExcludeNull.getFatJsonArray()
val genericListClassFromFatJsonArray = GenericListClassGeneratorByJSONArray(jsonKey, fatJsonArray.toString()).generate()
LogUtil.i("$tag jsonArray allItemAreArrayElement, return GenericListClass with generic type ${genericListClassFromFatJsonArray.name}")
return GenericListClass(generic = genericListClassFromFatJsonArray)
return GenericListClass(generic = genericListClassFromFatJsonArray, nullableElements = hasNulls)
}
else -> {
LogUtil.i("$tag jsonArray exception shouldn't come here, return GenericListClass with generic type ANY")
return GenericListClass(generic = KotlinClass.ANY)
return GenericListClass(generic = KotlinClass.ANY, nullableElements = true)
}
}
}
Expand All @@ -63,3 +62,18 @@ class GenericListClassGeneratorByJSONArray(private val jsonKey: String, jsonArra
return adjustPropertyNameForGettingArrayChildType(jsonKey)
}
}

internal fun readJsonArray(jsonArrayString: String): JsonArray {
val jsonArray = Gson().fromJson(jsonArrayString, JsonArray::class.java)
// if the last element is null, it may actually be a trailing comma
if (jsonArray.size() == 0 || !jsonArray.last().isJsonNull) {
return jsonArray
}
// check if the json array has a trailing comma
if (jsonArrayString.trimEnd().removeSuffix("]").trimEnd().endsWith(",")) {
val lastComma = jsonArrayString.lastIndexOf(",")
return Gson().fromJson(jsonArrayString.removeRange(lastComma..lastComma), JsonArray::class.java)
} else {
return jsonArray
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,20 @@ import wu.seal.jsontokotlin.utils.*
class ListClassGeneratorByJSONArray(private val className: String, jsonArrayString: String) {

private val tag = "ListClassGeneratorByJSONArray"
private val jsonArray: JsonArray = Gson().fromJson(jsonArrayString, JsonArray::class.java)
private val jsonArray: JsonArray = readJsonArray(jsonArrayString)
private val jsonArrayExcludeNull = jsonArray.filterOutNullElement()
private val hasNulls get() = jsonArray.size() != jsonArrayExcludeNull.size()

fun generate(): ListClass {

when {
jsonArray.size() == 0 -> {
LogUtil.i("$tag jsonArray size is 0, return ListClass with generic type ANY")
return ListClass(name = className, generic = KotlinClass.ANY)
return ListClass(name = className, generic = KotlinClass.ANY, nullableElements = true)
}
jsonArray.allItemAreNullElement() -> {
LogUtil.i("$tag jsonArray allItemAreNullElement, return ListClass with generic type ${KotlinClass.ANY.name}")
return ListClass(name = className, generic = KotlinClass.ANY)
return ListClass(name = className, generic = KotlinClass.ANY, nullableElements = true)
}
jsonArrayExcludeNull.allElementAreSamePrimitiveType() -> {

Expand All @@ -34,25 +35,25 @@ class ListClassGeneratorByJSONArray(private val className: String, jsonArrayStri
val p = jsonArrayExcludeNull[0].asJsonPrimitive;
val elementKotlinClass = if(p.isNumber) getKotlinNumberClass(jsonArrayExcludeNull) else p.toKotlinClass()
LogUtil.i("$tag jsonArray allElementAreSamePrimitiveType, return ListClass with generic type ${elementKotlinClass.name}")
return ListClass(name = className, generic = elementKotlinClass)
return ListClass(name = className, generic = elementKotlinClass, nullableElements = hasNulls)
}
jsonArrayExcludeNull.allItemAreObjectElement() -> {
val fatJsonObject = jsonArrayExcludeNull.getFatJsonObject()
val itemObjClassName = "${className}Item"
val dataClassFromJsonObj = DataClassGeneratorByJSONObject(itemObjClassName, fatJsonObject).generate()
LogUtil.i("$tag jsonArray allItemAreObjectElement, return ListClass with generic type ${dataClassFromJsonObj.name}")
return ListClass(className, dataClassFromJsonObj)
return ListClass(className, dataClassFromJsonObj, nullableElements = hasNulls)
}
jsonArrayExcludeNull.allItemAreArrayElement() -> {
val fatJsonArray = jsonArrayExcludeNull.getFatJsonArray()
val itemArrayClassName = "${className}SubList"
val listClassFromFatJsonArray = ListClassGeneratorByJSONArray(itemArrayClassName, fatJsonArray.toString()).generate()
LogUtil.i("$tag jsonArray allItemAreArrayElement, return ListClass with generic type ${listClassFromFatJsonArray.name}")
return ListClass(className, listClassFromFatJsonArray)
return ListClass(className, listClassFromFatJsonArray, nullableElements = hasNulls)
}
else -> {
LogUtil.i("$tag jsonArray exception shouldn't come here, return ListClass with generic type ANY")
return ListClass(name = className, generic = KotlinClass.ANY)
return ListClass(name = className, generic = KotlinClass.ANY, nullableElements = true)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,8 @@ class DataClassGeneratorByJSONObjectTest {

val glossDefP2 = glossDefDataClass.properties[1]
glossDefP2.name.should.be.equal("GlossSeeAlso")
glossDefP2.type.should.be.equal(GenericListClass(KotlinClass.STRING).name)
glossDefP2.type.should.be.equal(GenericListClass(KotlinClass.STRING, nullableElements = false).name)
glossDefP2.originJsonValue.should.be.empty
glossDefP2.typeObject.should.be.equal(GenericListClass(KotlinClass.STRING))
glossDefP2.typeObject.should.be.equal(GenericListClass(KotlinClass.STRING, nullableElements = false))
}
}
4 changes: 2 additions & 2 deletions src/test/kotlin/wu/seal/jsontokotlin/DataClassMakerTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,9 @@ class DataClassMakerTest {

val glossDefP2 = glossDefDataClass.properties[1]
glossDefP2.name.should.be.equal("GlossSeeAlso")
glossDefP2.type.should.be.equal(GenericListClass(KotlinClass.STRING).name)
glossDefP2.type.should.be.equal(GenericListClass(KotlinClass.STRING, nullableElements = false).name)
glossDefP2.originJsonValue.should.be.empty
glossDefP2.typeObject.should.be.equal(GenericListClass(KotlinClass.STRING))
glossDefP2.typeObject.should.be.equal(GenericListClass(KotlinClass.STRING, nullableElements = false))

}

Expand Down
Loading

0 comments on commit 2ed9370

Please sign in to comment.