-1

i have a string of this form:

[{"LocationsItems":[{"ItemId":4,"LocationId":3,"Qty":34},{"ItemId":19,"LocationId":3,"Qty":55}]}];

i need to convert this to an array of object, i tried this:

let data = convertedData.data(using: .utf8)!
        do {
            if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
            {
                print(jsonArray)

            } else {
                print("bad json")
            }
        } catch let error as NSError {
            print(error)
        }
    }

and returned this , which is an array of dictionaries:

[["LocationsItems": <__NSArrayI 0x600003a1c100>(
{
    ItemId = 4;
    LocationId = 3;
    Qty = 34;
},
{
    ItemId = 19;
    LocationId = 3;
    Qty = 55;
}
)
]]

how can i extract the objects from it? thanks

MrJ
  • 96
  • 10

1 Answers1

2

You can create a struct of LocationItem.

struct LocationItem {
    var itemId: Int?
    var locationId: Int?
    var qty: Int?    
}

var innerDictionary = jsonArray[0] as? [String: Any]
var arrayOfDict = innerDictionary["LocationsItems"] as? [[String: Any]]

var locationsItems = arrayOfDict.map { 
    LocationItem(itemId: $0["ItemId"], locationId: $0["LocationId"], qty: $0["Qty"]) 
}

Alternatively, you can use Codable:

struct LocationItem: Codable {
    var itemId: Int?
    var locationId: Int?
    var qty: Int?

    enum CodingKeys: String, CodingKey {
        case itemId = "ItemId"
        case locationId = "LocationId"
        case qty = "Qty"
    }
}

let decoder = JSONDecoder()

do {
    let responseStructure = try decoder.decode([[String:[[String:Any]]]], from: data)
} catch {
    // failed
}

let locationItems = responseStructure[0]["LocationsItems"]
George
  • 25,988
  • 10
  • 79
  • 133
Durdu
  • 4,649
  • 2
  • 27
  • 47