无法使用SwiftyJson正确解析Json

plupiseo  于 2023-01-16  发布在  Swift
关注(0)|答案(1)|浏览(141)

我有以下Json响应:

`       [Body]:
    {"id":"cmpl-6Z45N6vfd2312vdfqyYPb8aDRVe9Nft7vfnpoEsL","object":"text_completion","created":16738vfv15205,"model":"text-davinci-003","choices":[{"text":"\n1. Full Stack Developer\n2. Project Engineering Intern\n3. AI Programmer\n4. Systems Trade Studies Engineer\n5. BLE Technology Developer\n6. macOS Menu Bar App Developer\n7. Mobile App Developer\n8. Research Engineer\n9. Writing and Design Lab Researcher","index":0,"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":726,"completion_tokens":60,"total_tokens":786}}`

我使用SwiftyJson和Alamofire解析Json,代码如下:

`     AF.request(...).responseJSON { response in
                
                print("response: \(response)")
                
                
                switch response.result {
                case .success(_):
                    if let JSON = response.value as! [[String : Any]]?{
                               print("JSON: \(JSON)")
                        let dic = JSON[0] as [String:AnyObject]?
                               print("TitularEmail : ",dic?["choices"])
                           }
                       break

                   case .failure(_):
                       print("There is an error")
                       break
               }
        }`

但它不断打破,我不断得到错误'线程1:如果JSON = response,则发送SIGABRT“at”信号。值为!String:有没有?{'
有人知道哪里出了问题吗?我读过不少帖子,但我似乎不能弄清楚这一点。任何信息都将不胜感激。

zhte4eai

zhte4eai1#

使用内置的Decodable可能是一个更好的选择。冒着稍微偏离最初的SwiftyJSON问题的风险,我强烈推荐使用Decodable来解析JSON(另请参见Encodable的写作和Codable的组合)。下面是Decodable的一个非常基本的使用示例。假设您想要解析以下内容:

{
"name": "New York City",
"mayor": "Eric Adams",
"population": 8468000
}

使用Decodable可以非常容易地解析它:

struct City: Decodable {
    let name:String
    let mayor:String
    let population:Int
}

在本例中,您可以通过获取JSON(假设它存储在名为jsonData的变量中)并执行以下操作来创建City的示例:

let NYC = try JSONDecoder().decode(City.self, from: jsonData)

你应该高度考虑这条路线,因为它可以得到很多做很少的工作。
如果不想使用前面提到的解析方法,也可以使用JSONSerializationHere是一个简单的教程,介绍了如何做到这一点。
在您的情况下,可以实现Decodable来解决问题,如下所示:

var json = try! Data(contentsOf: URL(fileURLWithPath: "PATH TO FILE WITH EXAMPLE JSON TEXT"))

struct FirstStruct:Decodable {
    let id:String
    let object:String
    let created:String //I'm calling this a string because, despite the lack of quotes, it has letters in it and cannot be an Int. You could also do something like Int? so it can fail safely if there are letters. I am adding quotes to the example text make it work.
    let model:String
    let choices:[SecondStruct]
    let usage:ThirdStruct
    
}

struct SecondStruct:Decodable {
    let text:String
    let index:Int
    let logprobs:String? //idk what type this is supposed to be from the text given
    let finish_reason:String
}

struct ThirdStruct:Decodable {
    let prompt_tokens:Int
    let completion_tokens:Int
    let total_tokens:Int
}

var test = try! JSONDecoder().decode(FirstStruct.self, from: json)

print(test.id) 
print(test.usage.total_tokens) //these two examples show it clearly works here

显然,在错误处理方面要多加小心,try!对于这个示例来说更容易。

相关问题