I have an array which has set of objects var quiz_anwers_list = [QuizQu]()
"QuizQu" is a Class which contains 2 variables
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? I am a new to 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.
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)
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\\"}]")
Note: the output String is escaped, hence the backslashes
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.