如何使用Kotlinx序列化JSON的动态键

时间:2019-11-13 15:55:33

标签: kotlin serialization kotlinx.serialization

我有一个带有这种密钥的json:

...
    "metaData": {
        "date:create": "2019-11-13t15:42:02+01:00",
        "date:modify": "2019-11-13t15:42:02+01:00",
        "exif:ColorSpace": "1",
        "exif:ExifImageLength": "1500",
        "exif:ExifImageWidth": "1125",
        "exif:ExifOffset": "38",
        "exif:Orientation": "1",
        "jpeg:colorspace": "2",
        "jpeg:sampling-factor": "1x1,1x1,1x1"
    },
...

metaData对象中的所有键都是动态的(不是真的,但是有数百种不同的键)如何在不必创建具有所有可能键的类的情况下序列化此对象。

这是我的工作

@Serializable
data class Image(
    val name: String? = null,
    val uid: String,
    val createdAt: String? = null,
    val updatedAt: String? = null,
    val metaData: MetaData? = null,
)

@Serializable
data class MetaData (
    @SerialName("date:create")
    val dateCreate: String,

    @SerialName("date:modify")
    val dateModify: String,

    @SerialName("exif:ColorSpace")
    val exifColorSpace: String,

    @SerialName("exif:ExifImageLength")
    val exifExifImageLength: String,

    @SerialName("exif:ExifImageWidth")
    val exifExifImageWidth: String,

    @SerialName("exif:ExifOffset")
    val exifExifOffset: String,

    @SerialName("exif:Orientation")
    val exifOrientation: String,

    @SerialName("jpeg:colorspace")
    val jpegColorspace: String,

    @SerialName("jpeg:sampling-factor")
    val jpegSamplingFactor: String
)

1 个答案:

答案 0 :(得分:1)

您可以使用JSONObject动态序列化元数据。您的Metadata类对此解决方案无效,您的Image实例将具有一个JSONObject作为元数据属性:

data class Image(
    val name: String? = null,
    val uid: String,
    val createdAt: String? = null,
    val updatedAt: String? = null,
    val metaData: JSONObject? = null,
)