5

I have a json array in string format, however for some reason I cannot convert it to JSON array with SwiftyJSON. It might have something to do with json structure. How do I do it?

Here is the string

[{"Disabled":false,"Group":null,"Selected":false,"Text":"1","Value":"1"},{"Disabled":false,"Group":null,"Selected":false,"Text":"2","Value":"2"},{"Disabled":false,"Group":null,"Selected":false,"Text":"3","Value":"3"},{"Disabled":false,"Group":null,"Selected":false,"Text":"4","Value":"4"},{"Disabled":false,"Group":null,"Selected":false,"Text":"5","Value":"5"}]

Here is my code:

let json = JSON(jsonString)
0

5 Answers 5

8

You can use SwiftyJSON for that then you can get JSON like as follow.

import SwiftyJSON

let json = JSON(data: dataFromNetworking)
let json = JSON(jsonObject)
if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
    let json = JSON(data: dataFromString)
}

Edit: Swift 3

if let dataFromString = jsonString?.data(using: String.Encoding.utf8, allowLossyConversion: false) {
    let json = JSON(data: dataFromString)    
}
Sign up to request clarification or add additional context in comments.

Comments

6

You should cast your data to array like this way:

if let arr = (data as? JSON)?.array {
// do something with your array
}

1 Comment

what is 'data' here? our string ?
2

You can do like this:

let json = JSON(jsonString)
if let array = json?.array {
    // do something with array
}

Comments

0

Ended up doing this:

if let jsonString = json["Data"].string!.dataUsingEncoding(NSUTF8StringEncoding){

            let json = JSON(data: jsonString)
            print(json[0])

}

Comments

0

My problem resolved using this

    let objectData = responseString!.dataUsingEncoding(NSUTF8StringEncoding)
 let json = try NSJSONSerialization.JSONObjectWithData(objectData!, options: NSJSONReadingOptions.MutableContainers)
let myjson = JSON(json)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.