【发布时间】:2020-11-29 05:05:44
【问题描述】:
我是 Swift 和 IOS 开发的新手,我正在尝试将获取的 JSON 数据显示到文本标签上。
基本上,我的目标是仅将以下 API 调用结果的第一个对象显示到文本标签上(请参阅下面的示例)
要解码的 JSON:
[
{
"title":"Compound Hibernation",
"content":"Those who glance about me\nwho cease to see inside the Sun\nwho cease to imagine its destabilized pre-quanta\ncannot know me\ncannot know my ethos as pumice\nas mingled apparition or flare\n\nmy perception through the prior sun that I ingest\nlike a blackened pre-existence\nor collected hawks through assignation\n\nthe Sun\nwith its dualisms\nwith its pre-biotic photons which waver\n\nperhaps\n9 suns before the Sun existed \nbefore the oceans seemed formed \nthere were molecular drafts\n\nakashic precursors \nfloating proto-ammonia\n\nI think of carbon \n& wisps \n& floodings\n\nof feral combat shelter \nwhere blank geometry accrues\n\nbefore separable biology was born\nbefore the contradictory ballast of de-existent protozoa\n\nbeing scorching photon by abstentia \nlike a pre-atomic sigil \ndestabilized as blizzard\n\na pre-cognitive rotation\na strange galvanics of the cosmos\n\n& because of this galvanics\none reeks of invisible tremor\nwalking around in league with daunting helium affliction\n\nthus\nthe mirrors in my skin like haunted salamander fluid\nlike cells bereft with cooling centigrade rotation\n\ntherefore\nI know the abyss as volatile lunar transposition\nas sub-liminal mantis as climbing\nas splintering\n\ntherefore I am not\nan oily or blasphemous yogin\ncollapsing in default by sudden anger or water\n\nyet I am compound\nstruggling with scattered mental a-rhythmia\nwith partial psychic aphasia\nintensive\nillusive\naloof by interior compounding",
"url":"https:\/\/www.poemist.com\/will-alexander\/compound-hibernation",
"poet":{
"name":"Will Alexander",
"url":"https:\/\/www.poemist.com\/will-alexander"
}
},
{
"title":"His Lady Of The Sonnets Ix",
"content":"Last night\u2013or was it in the golden morn\u2013\nOnce more I dreamed that I alone did fare\nForth into spirit-silences; and there\nI found you not; my star was set! Forlorn,\nI sought the kindred company of worn\nAnd stricken souls\u2013lost, sundered souls, who bear\nOld and avoided crosses with each care\nWoven together in their crowns of thorn.\n\nGods of the patient, vain endeavour, these\nClaimed me and called me fellow, comrade, friend,\nAnd bade me join in their brave litanies;\nBecause, though I had failed you, I dared bend\nBefore you without hope of one reward,\nSave that in loving you my soul still soared.",
"url":"https:\/\/www.poemist.com\/robert-norwood\/his-lady-of-the-sonnets-ix",
"poet":{
"name":"Robert Norwood",
"url":"https:\/\/www.poemist.com\/robert-norwood"
}
},
]
为此,我创建了以下结构:
import Foundation
struct PoemData: Codable {
public var title: String
public var content: String
public var poet: Poet
}
struct Poet: Codable {
var name: String
}
这是我对 API 请求和 JSON 解码的尝试:
@State public var data = [PoemData(title: String("Poem Name"), content: String("Poem Content"), poet: Poet(name: "Poet Name"))]
func getData() {
let urlstring = "https://www.poemist.com/api/v1/randompoems"
let url = URL(string: urlstring)
URLSession.shared.dataTask(with: url!) {data, response, error in
DispatchQueue.main.async {
if let data = data {
do {
let decoder = JSONDecoder()
let decodedData = try decoder.decode([PoemData].self, from: data)
self.data = decodedData
} catch {
print (error)
}
}
}
}.resume()
}
我的最终目标是在以下文本标签上显示标题和内容:
Text(PoemData.title[0])
.font(.largeTitle)
.fontWeight(.heavy)
.foregroundColor(.black)
.padding(.bottom, 40)
Text("Poem Body" as String)
.font(.body)
.foregroundColor(.black)
.lineSpacing(6)
但是,我不确定在文本标签中输入什么内容。我尝试了多种变体,例如Text(PoemData.title[0]),但是没有一个真正奏效。
感谢任何帮助!
提前致谢
【问题讨论】:
-
PoemData.title[0]没有意义,是吗?PoemData是模型类的名称。它不是实例化结果的对象名称。 -
感谢您的意见。你有什么建议呢?
-
if let first = data.first { Text(first.title) }