我正在尝试创建一个简单的应用程序,其中的数据是从json文件加载的。
我的json文件的名称是:
summary.json
它包含以下内容:
{
"name": "Octavio",
"lastName": "Rojas",
"email": "octavio.rojas@globant.com",
"phone": "5581723801",
"degree": "Bachelors degree in international business and trade",
"summary": "I just turned two years old in Globant on April 3rd 2019, I’ve been working with Disney for all this time in different areas of their parks app like resort reservations, profile and payment methods, geolocation services and itinerary information during my time here I’ve been working on sustainment, increasing code coverage, automation, analytics, developing tests, doing refactors and developing critical components for the frameworks I’ve been assigned to. I’ve worked with all kinds of computers since childhood, I’ve also participated in different activities related with computer science and information technologies, like database development, technical support, unix systems administration, web development, flash development and iOS development."
}
我正在尝试使用这个函数来读取它:
func loadJson() {
do {
guard let url = Bundle.main.url(forResource: "summary", withExtension: "json") else {
return
}
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(Person.self, from: data)
} catch {
print(error)
}
}
我的struct看起来像这样:
struct Person: Encodable {
let name: String
let lastName: String
let email: String
let phone: String
let degree: String
let summary: String
}
但每次我尝试解码数据的时候
let jsonData = try decoder.decode(Person.self, from: data)
我得到了这个错误:
dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Badly formed object around character 88." UserInfo={NSDebugDescription=Badly formed object around character 88.})))
如果不是尝试加载json文件,而是将其放在类中,如下所示:
let data = """
{
"name": "Octavio",
"lastName": "Rojas",
"email": "octavio.rojas@globant.com"
"phone": "5581723801"
"degree": "Bachelors degree in international business and trade"
"summary": "I just turned two years old in Globant on April 3rd 2019, I’ve been working with Disney for all this time in different areas of their parks app like resort reservations, profile and payment methods, geolocation services and itinerary information during my time here I’ve been working on sustainment, increasing code coverage, automation, analytics, developing tests, doing refactors and developing critical components for the frameworks I’ve been assigned to. I’ve worked with all kinds of computers since childhood, I’ve also participated in different activities related with computer science and information technologies, like database development, technical support, unix systems administration, web development, flash development and iOS development."
}""".data(using: .utf8)
然后它起作用了,为什么这是这样的,我做错了什么?
提前谢谢。
https://stackoverflow.com/questions/56264324
复制相似问题