KNP
KNP

Reputation: 65

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

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

Upvotes: 3

Views: 249

Answers (3)

NinjaDeveloper
NinjaDeveloper

Reputation: 1712

you can do simple swift like this you. can use Web App like https://app.quicktype.io/ to convert JSON to swift structs :)

import Foundation

// MARK: - NameAge
struct NameAge: Codable {
    let name, age: Age
}

// MARK: - Age
struct Age: Codable {
    let id, label: String
    let disabled, display: Bool
    let pattern, type: String
}

let JSON = """
{
    "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"
   }
}
"""
let jsonData = JSON.data(using: .utf8)!
let nameAge = try? newJSONDecoder().decode(NameAge.self, from: jsonData)

Upvotes: 1

gcharita
gcharita

Reputation: 8327

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)
}

Upvotes: 2

Anjali Aggarwal
Anjali Aggarwal

Reputation: 629

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")
  }

Upvotes: 3

Related Questions