Turn Swift Object into a JSON String

How to serialize or convert Swift objects to JSON?

In Swift 4, you can inherit from the Codable type.

struct Dog: Codable {
var name: String
var owner: String
}

// Encode
let dog = Dog(name: "Rex", owner: "Etgar")

let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(dog)
let json = String(data: jsonData, encoding: String.Encoding.utf16)

// Decode
let jsonDecoder = JSONDecoder()
let secondDog = try jsonDecoder.decode(Dog.self, from: jsonData)

How to Serialise a model object into JSON String - Swift 3

Add a property jsonRepresentation to the class:

var jsonRepresentation : String {
let dict = ["userLoginId" : userLoginId, "searchString" : searchString, "tableName" : tableName]
let data = try! JSONSerialization.data(withJSONObject: dict, options: [])
return String(data:data, encoding:.utf8)!
}

By the way: Class names in Swift are supposed to start with a capital letter.

And don't use optionals as a laziness alibi not to write initializers...

Update:

In Swift 4 there is a smarter way: Remove jsonRepresentation and adopt Codable

public class CompanyRequestModel : Codable { ...

then use JSONEncoder

let data = try JSONEncoder().encode(objGetCompany)
let jsonString = String(data: data, encoding: .utf8)!

Convert Json string to Json object in Swift 4

The problem is that you thought your jsonString is a dictionary. It's not.

It's an array of dictionaries.
In raw json strings, arrays begin with [ and dictionaries begin with {.


I used your json string with below code :

let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = string.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
{
print(jsonArray) // use the json here
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}

and I am getting the output :

[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]

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

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

How to convert JSON array objects into list array | Swift 5

First of all please name structs and classes always with starting uppercase letter and declare the struct members non-optional if the API sends consistent data

struct TestStructure: Decodable {
let name: String
let orderid: Int
let trialid: Int
}

Second of all the decoding line doesn't compile, you have to write

let nav = try JSONDecoder().decode([TestStructure].self, from: data)

To get an array of all trialid values just map it

let allTrialids = nav.map(\.trialid)

Update: Take the compiler's advice and add explicit type to disambiguate

self.viewControllers = nav.map { test -> UIViewController in
let selected = UIImage(named: "Tab4_Large")!
let normal = UIImage(named: "Tab4_Large")!
let controller = storyboard!.instantiateViewController(withIdentifier: String(test.trialid))
controller.view.backgroundColor = UIColor.white
controller.floatingTabItem = FloatingTabItem(selectedImage: selected, normalImage: normal)
return controller
}


Related Topics



Leave a reply



Submit