4

我有一个带有这种键的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
)
4

1 回答 1

3

您可以使用 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,
)
于 2019-11-13T16:12:16.377 回答