93

I try to convert JSON string to a JSON object but after JSONSerialization the output is nil in JSON.

Response String:

[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]

I try to convert this string with my code below:

let jsonString = response.result.value
let data: Data? = jsonString?.data(using: .utf8)
let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String:AnyObject]
 print(json ?? "Empty Data")
3
  • did you added the alamofire pod. google.com/… Commented Nov 14, 2017 at 8:57
  • Yes I installed Alamofire Pod Commented Nov 14, 2017 at 8:59
  • Use a do ... catch instead and print the error. It'll probably tell you what's wrong. Commented Nov 14, 2017 at 9:32

5 Answers 5

139

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]]
Sign up to request clarification or add additional context in comments.

3 Comments

How we get the value from "jsonArray". I am trying if let name = jsonArray["name"] as? String { // no error } which is giving the error "Cannot subscript a value of type '[Dictionary<String, Any>]' with an index of type 'String'"
@Androidiseverythingforme : That's an array of dictionary, try let form_name = jsonArray[0]["form_name"] as? String and you will get the output.
this was the solution for me too , i was getting a raw json from url , and was unable to read it as an array because it was a string; so the line : " let data = string.data(using: .utf8)! " mentionned in this solution was what solved it , Thank you sir
42

Using JSONSerialization always felt unSwifty and unwieldy, but it is even more so with the arrival of Codable in Swift 4. If you wield a [String:Any] in front of a simple struct it will ... hurt. Check out this in a Playground:

import Cocoa

let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)!

struct Form: Codable {
    let id: Int
    let name: String
    let description: String?

    private enum CodingKeys: String, CodingKey {
        case id = "form_id"
        case name = "form_name"
        case description = "form_desc"
    }
}

do {
    let f = try JSONDecoder().decode([Form].self, from: data)
    print(f)
    print(f[0])
} catch {
    print(error)
}

With minimal effort handling this will feel a whole lot more comfortable. And you are given a lot more information if your JSON does not parse properly.

3 Comments

am I the only one who gets "Type 'Form' does not conform to protocol 'Decodable'" ?
You would have to post your code (in another question, not a comment, there it will look horrible) and your Swift version in order for anyone to help.
remove "import Cocoa" for Swift 5 then it works. thanks!
17

I tried the solutions here, and as? [String:AnyObject] worked for me:

do{
    if let json = stringToParse.data(using: String.Encoding.utf8){
        if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
            let id = jsonData["id"] as! String
            ...
        }
    }
}catch {
    print(error.localizedDescription)

}

1 Comment

id is nil for me.
8

I used below code and it's working fine for me. :

let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
    
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
        
     do {
            dictonary =  try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
        
            if let myDictionary = dictonary
              {
                  print(" User name is: \(myDictionary["userName"]!)")
              }
            } catch let error as NSError {
            
            print(error)
         }
}

Comments

-1
static func getJSONStringFromObject(object: Any?) -> String? {
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: object ?? DUMMY_STRING, options: [])
        return String(data: jsonData, encoding: .utf8) ?? DUMMY_STRING
    } catch {
        print(error.localizedDescription)
    }
    return DUMMY_STRING
}

1 Comment

this does the oposite from what OP wants

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.