Convert Array to JSON String in Swift

Convert array to JSON string in swift

As it stands you're converting it to data, then attempting to convert the data to to an object as JSON (which fails, it's not JSON) and converting that to a string, basically you have a bunch of meaningless transformations.

As long as the array contains only JSON encodable values (string, number, dictionary, array, nil) you can just use NSJSONSerialization to do it.

Instead just do the array->data->string parts:

Swift 3/4

let array = [ "one", "two" ]

func json(from object:Any) -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
return nil
}
return String(data: data, encoding: String.Encoding.utf8)
}

print("\(json(from:array as Any))")

Original Answer

let array = [ "one", "two" ]
let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil)
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)

although you should probably not use forced unwrapping, it gives you the right starting point.

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 array of dictionary to JSON?

A simple way to achieve that is to just extend CollectionType.

Use optional binding and downcasting, then serialize to data, then convert to string.

extension CollectionType where Generator.Element == [String:AnyObject] {
func toJSONString(options: NSJSONWritingOptions = .PrettyPrinted) -> String {
if let arr = self as? [[String:AnyObject]],
let dat = try? NSJSONSerialization.dataWithJSONObject(arr, options: options),
let str = String(data: dat, encoding: NSUTF8StringEncoding) {
return str
}
return "[]"
}
}

let arrayOfDictionaries: [[String:AnyObject]] = [
["abc":123, "def": "ggg", "xyz": true],
["abc":456, "def": "hhh", "xyz": false]
]

print(arrayOfDictionaries.toJSONString())

Output:

[
{
"abc" : 123,
"def" : "ggg",
"xyz" : true
},
{
"abc" : 456,
"def" : "hhh",
"xyz" : false
}
]

How to convert array object to JSON string . IOS 8 . Swift 1.2

If you want to use builtin functions like NSJSONSerialization (
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/ )
you basically need to convert all your objects to arrays, dictionaries, strings and numbers

In your case this should work, converting your objects to dictionaries before converting to a JSON string:

    let jsonCompatibleArray = AuditActivityDayListJson.map { model in
return [
"DayNumber":model.DayNumber,
"DayType":model.DayType,
"DayDateDisplay":model.DayDateDisplay,
"DayDate":model.DayDate
]
}
let data = NSJSONSerialization.dataWithJSONObject(jsonCompatibleArray, options: nil, error: nil)
let jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding)

For more complex scenarios I recommend SwiftyJSON ( https://github.com/SwiftyJSON/SwiftyJSON ) which makes error handling and more much easier.

How to convert an array of multiple object types to JSON without missing any object attribute in Swift?

class SUVCar: Car
{
enum SUVCarKeys: CodingKey {
case weight
}
var weight: Int

init(_ weight: Int)
{
self.weight = weight
super.init(brand: "MyBrand")
}

override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: SUVCarKeys.self)
try container.encode(weight, forKey: .weight)
try super.encode(to: encoder)
}
}

If you augment the subclass's implementation of encode then you can add in additional properties

Convert Array model object into JSON - Swift 5

Your custom type conforms to the Codable protocol so make use of that instead

func convertChainsIntoJSON(chains: [AllChainsItemsClassAModel]) -> String? {
guard let data = try? JSONEncoder().encode(chains) else { return nil }
return String(data: data, encoding: String.Encoding.utf8)
}


Related Topics



Leave a reply



Submit