Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive a json string and convert that into Dictionary?

Tags:

json

ios

swift

I have one JSON pasted below

{
    "name" :
    {
        "id" : "name",
        "label" : "name field",
        "disabled" : false,
        "display" : true,
        "pattern" : "^\\+(?:[0-9] ?){6,14}[0-9]$",
        "type" : "text"
    },
     "age" :
   {
    "id" : "age",
    "label" : "age",
    "disabled" : false,
    "display" : true,
    "pattern" : "^\\+(?:[0-9] ?){6,14}[0-9]$",
    "type" : "text"
   }
}

I need to pass this JSON string into my method and convert that into a Dictionary of Dictionary type Dictionary<String,Dictionary<String,Any>>

To do this first i tried to validate the JSON string before passing to a method and its always saying invalid json

let jsonData = json.data(using: String.Encoding.utf8)

   if JSONSerialization.isValidJSONObject(jsonData) {
       print("Valid Json")
   } else {
       print("InValid Json")
   }

any idea why this JSON string always returning invalid json?

I have tried this in playground please check the screenshot enter image description here

like image 915
KNP Avatar asked Nov 18 '25 23:11

KNP


2 Answers

You are checking data as isValidJsonObject and that is why it is giving invalid json. You should try converting the data to a jsonObject and then check isValidJsonObject

I tried as below and it gives Valid json

 let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])

 let jsonObject = try!JSONSerialization.jsonObject(with: jsonData, options: [])

 if JSONSerialization.isValidJSONObject(test) {
               print("Valid Json")
  } else {
               print("InValid Json")
  }
like image 137
Anjali Aggarwal Avatar answered Nov 20 '25 15:11

Anjali Aggarwal


You need to escape the 2 escape characters in the pattern property to pass the validation check of the JSONSerialization:

{
  "name": {
    "id": "name",
    "label": "name field",
    "disabled": false,
    "display": true,
    "pattern": "^\\\\+(?:[0-9] ?){6,14}[0-9]$",
    "type": "text"
  },
  "age": {
    "id": "age",
    "label": "age",
    "disabled": false,
    "display": true,
    "pattern": "^\\\\+(?:[0-9] ?){6,14}[0-9]$",
    "type": "text"
  }
}

then using jsonObject(with:options:) function of JSONSerialization will not give you an error:

do {
    if let dict = try JSONSerialization.jsonObject(with: Data(jsonString.utf8)) as? [String: Any] {
        print(dict)
    }
} catch {
    print(error)
}

Update: Even better, you can use Codable protocol to create a model structure:

struct Response: Codable {
    var name: Name
    var age: Age
}

struct Name: Codable {
    var id: String
    var label: String
    var disabled: Bool
    var display: Bool
    var pattern: String
    var type: String
}

struct Age: Codable {
    var id: String
    var label: String
    var disabled: Bool
    var display: Bool
    var pattern: String
    var type: String
}

and map your JSON directly to that model using JSONDecoder:

let decoder = JSONDecoder()

do {
    let decoded = try decoder.decode(Response.self, from: Data(jsonString.utf8))
    print(decoded)
} catch {
    print(error)
}
like image 41
gcharita Avatar answered Nov 20 '25 15:11

gcharita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!