简体   繁体   English

如何在iOS Swift中将对象数组转换为Json数组或Json字符串?

[英]How to convert object array into Json array or Json string in ios swift?

I have an array which has set of objects var quiz_anwers_list = [QuizQu]() "QuizQu" is a Class which contains 2 variables 我有一个数组,其中有一组对象var quiz_anwers_list = [QuizQu]() “ QuizQu”是一个包含2个变量的类

class QuizQu: Decodable {
    var ques_id: String?
    var their_answer: String?
}

Now am having, 现在有

for i in 0...self.quiz_anwers_list.count-1{

            print(self.quiz_anwers_list[i].ques_id ?? "no val in ques id of \(i)")
            print(self.quiz_anwers_list[i].their_answer ?? "no val in their_ans of \(i)")
        }

The output of those print is: 这些打印的输出是:

14
correct_answer
15
correct_answer2
16
correct_answer2
17
correct_answer

Now how can I convert this into JsonArray or JSON String? 现在如何将其转换为JsonArray或JSON String? I am a new to iOS. 我是iOS的新手。

Your class should probably be a struct and should conform to Encodable , not Decodable , if you plan to encode and decode you can use the Codable protocol which covers both cases. 您的类可能应该是一个结构,并且应该符合Encodable而不是Decodable ,如果您打算编码和解码,则可以使用涵盖两种情况的Codable协议。

Once you have done that, just use JSONEncoder to convert it to JSON data and then you can print it using String(bytes: Sequence, encoding: String.Encoding) 完成此操作后,只需使用JSONEncoder将其转换为JSON数据,然后即可使用String(bytes: Sequence, encoding: String.Encoding)打印它

struct QuizQu: Codable {
    var ques_id: String?
    var their_answer: String?
}

let questions = [
    QuizQu(ques_id: "1", their_answer: "2"),
    QuizQu(ques_id: "2", their_answer: "2"),
    QuizQu(ques_id: "3", their_answer: "1"),
    QuizQu(ques_id: "4", their_answer: "4"),
    QuizQu(ques_id: "5", their_answer: "3")
]

do {
    let encoded = try JSONEncoder().encode(questions)
    print(String(bytes: encoded, encoding: .utf8))
} catch {
    print(error)
}

Output: 输出:

Optional("[{\\"ques_id\\":\\"1\\",\\"their_answer\\":\\"2\\"},{\\"ques_id\\":\\"2\\",\\"their_answer\\":\\"2\\"},{\\"ques_id\\":\\"3\\",\\"their_answer\\":\\"1\\"},{\\"ques_id\\":\\"4\\",\\"their_answer\\":\\"4\\"},{\\"ques_id\\":\\"5\\",\\"their_answer\\":\\"3\\"}]") 可选( “[{\\” ques_id \\ “:\\” 1 \\” \\ “their_answer \\”:\\ “2 \\”},{\\ “ques_id \\”:\\ “2 \\” \\ “their_answer \\”:\\ “2 \\”},{\\ “ques_id \\”:\\ “3 \\” \\ “their_answer \\”:\\ “1 \\”},{\\ “ques_id \\”:\\ “4 \\” \\ “their_answer \\” :\\ “4 \\”},{\\ “ques_id \\”:\\ “5 \\”,\\ “their_answer \\”:\\ “3 \\”}]“)

Note: the output String is escaped, hence the backslashes 注意:输出的String被转义,因此反斜杠

You can do it with 你可以做到

    extension Encodable {
      var dictionary: [String: Any]? {
        guard let data = try? JSONEncoder().encode(self) else { return nil }
        return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
      }
}

let struct = QuizQu(ques_id: 1, their_answer: abc)
let jsonObj = struct.dictionary

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM