【问题标题】:Different json format for encode Swift用于编码 Swift 的不同 json 格式
【发布时间】:2020-03-30 22:15:09
【问题描述】:

我尝试为 JSON 编码准备数据:

var i = 0
for (data) in students {
    var variableNewData = ["\(students[i].id)":["timestampValue":"\(students[i].timestampValue)"]]
    variableNewData["updateTime"] = ["updateTime":"\(students[i].timestampValue)"]
    variableNewData["createTime"] = ["createTime":"\(students[i].timestampValue)"]
    i += 1

    let finalParameter = ["class":variableNewData]
    print("LastParameter:",finalParameter)}
}

我需要这种格式的数据:

{"class": {"studentOne": {"timestampValue": "2020-02-04" },"studentTwo ":{ "timestampValue": "2020-02-05" }},"createTime": "2020-03-30","updateTime": "2020-03-30"}

但我明白了:class、id、timestampValue 似乎没问题,但创建和更新时间是错误的。 感谢您的任何建议。

{"class":{"createTime":{"createTime":"2020-03-30"},"studentOne":{"timestampValue":"2020-02-04"},"updateTime":{"createTime":"2020-03-30"}}}

【问题讨论】:

  • 顺便说一句,您是否喜欢这种结构,其中此class 字典中的键由学生ID 键控?在 class 内的键中包含唯一标识符会使创建和使用此 JSON 变得更加困难。一个简单的字典数组更容易处理...

标签: arrays json swift


【解决方案1】:

让我们看看你想要的“漂亮”格式:

{
    "class": {
        "studentOne": {
            "timestampValue": "2020-02-04"
        },
        "studentTwo ": {
            "timestampValue": "2020-02-05"
        }
    },
    "createTime": "2020-03-30",
    "updateTime": "2020-03-30"
}

因此,对于键 class,您有一个值,它是由学生 ID 键入的子字典,它本身包含另一个具有单个时间戳的字典。所以,我会先建立这个与class相关的字典:

var studentsDictionary: [String: [String: String]] = [:]
for student in students {
    studentsDictionary[student.id] = ["timestampValue": student.timestampValue]
}

然后你有createTimeupdateTime 在顶层,还有class(大概是整个班级的创建和更新数据,而不是个别学生)。无论如何,您可以构建顶级字典,如下所示:

let dictionary: [String: Any] = [
    "class": studentsDictionary,
    "updateTime": "2020-02-05",
    "createTime": "2020-02-05"
]

显然,您希望为类的时间戳值设置 updateTimecreateTime,但希望这能说明这个想法。

然后我们可以构建所有这些的 JSON 表示:

let data = try! JSONSerialization.data(withJSONObject: dictionary) // add `option: .prettyPrinted` if you want to see pretty version

//
// if you want to check the above `data`:
//
// let string = String(data: data, encoding: .utf8)!
// print(string)
//

请注意,updateTimecreateTime 不是学生级别的,所以我不确定您想从哪里获得这些值。


顺便说一句,如果您有兴趣,构建studentDictionary 字典的更简洁方法是使用Dictionary(uniqueKeysWithValues:)

let studentsDictionary = Dictionary(uniqueKeysWithValues: students.map { student in
    (student.id, ["timestampValue": student.timestampValue])
})

【讨论】:

  • 编码不序列化可以做到吗?
  • 你可以,但要困难得多。并且不建议这样做,因为它打开了一罐关于正确格式化 JSON 的蠕虫(某些字符需要转义,其他字符需要编码等)。
【解决方案2】:

尝试将 updateTimecreateTime 键值设置为简单的字符串,而不是它们自己的字典。

variableNewData["updateTime"] = "\(students[i].timestampValue)"
variableNewData["createTime"] = "\(students[i].timestampValue)"

【讨论】:

  • 我试了一下,但我得到 Cannot assign value of type 'String' to type '[String : String]?'
猜你喜欢
  • 2015-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-26
  • 2023-03-14
  • 1970-01-01
  • 2017-12-23
  • 2023-03-20
相关资源
最近更新 更多