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
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")
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With