Test Test
Test Test

Reputation: 1901

JSON to Array conversion

I'm trying to convert a JSON string to an array. The JSON string is:

[
  {
    "field_value" : "28 Aug 2017",
    "field_data_type_combo_value" : "",
    "field_data_type_category_id" : "1",
    "form_id" : "19",
    "field_id" : "133",
    "message_unique_id" : "7941501245582800298",
    "field_data_type_combo_id" : "0",
    "field_data_type_id" : "1"
  },
  {
    "field_value" : "",
    "field_data_type_combo_value" : "",
    "field_data_type_category_id" : "9",
    "form_id" : "19",
    "field_id" : "134",
    "message_unique_id" : "7941501245582714588",
    "field_data_type_combo_id" : "0",
    "field_data_type_id" : "26"
  },
  {
    "field_value" : "hk",
    "field_data_type_combo_value" : "",
    "field_data_type_category_id" : "6",
    "form_id" : "19",
    "field_id" : "135",
    "message_unique_id" : "7941501245582699681",
    "field_data_type_combo_id" : "0",
    "field_data_type_id" : "17"
  }
]

and my conversion code is

if let data = text.data(using: .utf8) {
    do {
        return try JSONSerialization.jsonObject(with: data, options: .mutableContainers)  as? [String : AnyObject]
    } catch {
        print(error.localizedDescription)
    }
}

The conversion result is always nil. I also checked that JSON string in Online JSON Viewer and the string is correct. Please help me guys.

Upvotes: 0

Views: 83

Answers (2)

gnasher729
gnasher729

Reputation: 52602

You explicitely write in your call:

as? [String: AnyObject]

In other words, you ask Swift to take whatever JSON returned, check that it is a dictionary with String keys, and either return that dictionary or nil. Since your data is an array and not a dictionary, it returns nil. Exactly what you asked for, but not what you wanted.

What you are expecting is an array of dictionaries, not a dictionary. You should also use Any instead of AnyObject. So convert it using

as? [[String: Any]]

The outer [] means it is an array, the inner [String: Any] means the items in the array must be dictionaries with String keys and Any values.

And why are you using .mutableContainers? If you have a good reason that you can explain then use it. If you don't and just copied the code from somewhere then remove it.

Upvotes: 1

luk2302
luk2302

Reputation: 57164

That json isn't a dictionary on the top level but an array. You can see that from the [ ... ], it would be a dictionary if it was { ... }. Fix your code using the corresponding cast:

return try JSONSerialization.jsonObject(with: data, options: .mutableContainers)  as? [AnyObject]

Upvotes: 1

Related Questions