Rajat Attri
Rajat Attri

Reputation: 73

Convert below mentioned Json String to Dictionary

Below mentioned is my JSON String:

{
"StoreID": "ABC012",
"BillNo": "A000000001",
"Amount":  "1234.56",
"Auth": 96fc3411-dfa5-4df7-ada8-25b8a58ef1ea
}

I am using below mentioned code to convert

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

It is returning nil for the above-mentioned case but is working fine for:

{
"StoreID": "BC007",
"BillNo": "M170000351",
"Amount": 1818.96
}

I don't know what is the case, error.localizedDescription == The data couldn’t be read because it isn’t in the correct format.

Upvotes: 1

Views: 80

Answers (3)

foxen
foxen

Reputation: 9

Value 96fc3411-dfa5-4df7-ada8-25b8a58ef1ea of Auth key is not doubleqouted ( "" ) . So it is not a valid datatype for json format.

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

You need

1-

struct Root: Codable {
    let storeID, billNo, amount, auth: String

    enum CodingKeys: String, CodingKey {
        case storeID = "StoreID"
        case billNo = "BillNo"
        case amount = "Amount"
        case auth = "Auth"
    }
}

2-

{
    "StoreID": "ABC012",
    "BillNo": "A000000001",
    "Amount":  "1234.56",
    "Auth": "96fc3411-dfa5-4df7-ada8-25b8a58ef1ea"
}

3-

func convertToDictionary(text: String) -> Root? {
  return try? JSONDecoder().decode(Root.self, from: text.data(using:.utf8)!)
}

Upvotes: 1

David Pasztor
David Pasztor

Reputation: 54706

You first JSON is invalid. You need to put Strings in quotes and the value assigned to Auth is a String.

{
"StoreID": "ABC012",
"BillNo": "A000000001",
"Amount":  "1234.56",
"Auth": "96fc3411-dfa5-4df7-ada8-25b8a58ef1ea"
}

You should always confirm that your JSON is valid if in doubt, this is one tool you can use for that.

Upvotes: 2

Related Questions