【发布时间】:2020-02-26 19:51:40
【问题描述】:
我当然希望能得到一些帮助。我正在使用 Swift 5.1。 我正在尝试获取当前日期(date4)并将其格式化为三个字母的月份缩写。没问题,那部分工作正常。然后我定义了一个名为 (currentMonthDate) 的常量,它包含三个字母月份和字符串“MoonData”的连接。结果如下所示:“FebMoonData” - 到目前为止,所有工作都按设计进行。
我的 Json 是按月分开的。下面显示的是价值两个月的 Json 作为缩写示例。显然,我的模型旨在适应 Json 结构 - 不包括在内。现在的问题。如果您查看 JSONDecoder 代码行,您会注意到我正在尝试在解码器代码行中使用串联字符串“currentMonthDate”。我的想法是,随着每个新月份的到来,data4 将发生变化,而 currentMonthDate 将反映该变化,然后会找到反映该特定月份的 JSON 数据块。我收到的错误是:无法将“字符串”类型的值转换为预期的参数类型“数据” 为了清楚起见,如果我在解码器行中简单地键入 FebMoonData(Feb 的 Json 块的名称),它会按预期工作。也就是说,它找到名为 FebMoonData 的 Json 数组。谢谢!
// JSON
let FebMoonData = """
[
{"time":"20 Feb 2020 00:00 UT"}
]
""".data(using: .utf8)!
let MarMoonData =
[
{"time":"20 Feb 2020 00:00 UT"}
]
""".data(using: .utf8)!
// End JSON
let date4 = Date()
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "MMM"
let currentMonthDate = dateFormatterGet.string(from: date4) + "MoonData"
let moonphase = try! JSONDecoder().decode([MoonPhase].self, from: currentMonthDate)
【问题讨论】:
-
let MarMoonData =之后的字符串文字的前导"""缺失。 -
显示您的
MoonPhase声明。顺便说一句,您的currentMonthDate它不是有效的 JSON 数组。请查看如何提供minimal reproducible example
标签: json swift decoder dateformatter