JSON support using Gson

预计阅读时间:1分钟

GSON功能可让您使用google-gson库轻松处理应用程序中的JSON内容.

此功能是ContentNegotiation转换器.

此功能定义在类io.ktor.gson.GsonConverter在神器io.ktor:ktor-gson:$ktor_version .
dependencies { implementation "io.ktor:ktor-gson:$ktor_version" }
dependencies { implementation("io.ktor:ktor-gson:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-gson</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

Basic usage

通过使用Gson注册JSON内容转换器来安装功能:

install(ContentNegotiation) {
    gson {
        // Configure Gson here
    }
}

gson块是用于以下目的的便捷方法:

register(ContentType.Application.Json, GsonConverter(GsonBuilder().apply {
    // ...
}.create()))

Configuration

里面的gson块,你可以访问GsonBuilder用于安装ContentNegotiation. 让您了解可用的内容:

install(ContentNegotiation) {
    gson {
        setPrettyPrinting()
        
        disableHtmlEscaping()
        disableInnerClassSerialization()
        enableComplexMapKeySerialization()

        serializeNulls()

        serializeSpecialFloatingPointValues()
        excludeFieldsWithoutExposeAnnotation()
        
        setDateFormat(...)

        generateNonExecutableJson()

        setFieldNamingPolicy()
        setLenient()
        setLongSerializationPolicy(...)
        setExclusionStrategies(...)
        setVersion(0.0)
        addDeserializationExclusionStrategy(...)
        addSerializationExclusionStrategy(...)
        excludeFieldsWithModifiers(Modifier.TRANSIENT)
        
        registerTypeAdapter(...)
        registerTypeAdapterFactory(...)
        registerTypeHierarchyAdapter(..., ...)
    }
}

by  ICOPY.SITE