Parsing nested Array of Dictionaries using Object Mapper
Your first model will represent outer array. And second will represent inner array. Here is a sample
import Foundation
import ObjectMapper
// RecipientModel is an array itself
class RecipientModel: Mappable {
var filingStatusId:Int
var orderId: Int
var formName: String
var recipientList: [RecipientList]
required init?(_ map: Map) {
filingStatusId = 0
orderId = 0
formName = ""
recipientList = []
}
func mapping(map: Map) {
filingStatusId <- map["FilingStatusId"]
orderId <- map["OrderId"]
formName <- map["FormName"]
recipientList <- map["RecipientList"]
}
}
And now you will create another model for your RecipientList
class RecipientList: Mappable {
var filingStatusId:Int
var formId: Int
var formName: String
required init?(_ map: Map) {
filingStatusId = 0
formId = 0
formName = ""
}
func mapping(map: Map) {
filingStatusId <- map["FilingStatusId"]
formId <- map["FormId"]
formName <- map["FormName"]
}
}
How to Parse Nested Value Into List From JSON Array Using Jackson
Without having tried it, this looks like a JSON-file that would come from serializing a Sightings-object from something like
public AnimalSighting {
public int id;
public String name;
public String location;
}
public Sightings {
public int count;
public ArrayList results;
}
Then deserialization would be straightforward with new ObjectMapper().readValue(file, Sightings.class);
Of course the classes could use private attributes with getters and setters and then possibly need some annotations (@JsonCreator/@JsonProperty/@JsonGetter/@JsonSetter, depending on what exactly you are doing), but the general principle remains.
Parsing a nested dictionary with arbitrary numerical keys and object array values
Since question is how you can parse entry1
to Dictionary
- easiest option is:
JToken root = JToken.Parse(testJson);
Dictionary descriptions = root["entry1"].ToObject>();
Json.NET allows mixing of .NET classes (Dictionary
) and his own classes (JArray
) without problems when parsing.
ObjectMapper and arrays with unique keys
Use Codable
to parse the above JSON response.
Models:
struct Rooms: Codable {
let rooms: [String:Room]
}
struct Room: Codable {
let id: String
let area: Area
}
struct Area: Codable {
let squareFeet: Int
let squareMeters: Int
}
Parse the JSON data
like so,
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let response = try decoder.decode(Rooms.self, from: data)
print(response.rooms.first?.key) //for the above json it will print "165476"
} catch {
print(error)
}
How to represent a dictionary in Swift with nested types from JSON
I recommend that you look at ObjectMapper and AlamofireObjectMapper frameworks, both available on Cocoapods. With them, mapping from JSON to Swift's object is really easy.
First, define how the JSON maps to your object:
import ObjectMapper
class User: Mappable {
var id: String?
var username: String?
var accounts: UserAccount?
var followers: Int?
var following: Int?
required init?(_ map: Map) { /* validate your JSON, etc */ }
func mapping(map: Map) {
self.id <- map["id"]
self.username <- map["username"]
self.accounts <- map["accounts"]
self.followers <- map["followers"]
self.following <- map["following"]
}
}
class UserAccount: Mappable {
var verifiedEmail: Bool?
var identities: [UserIdentity]?
required init?(_ map: Map) { }
func mapping(map: Map) {
self.verifiedEmail <- map["verified_email"]
self.identities <- map["identities"]
}
}
class UserIdentity: Mappable {
var network: String?
var token: String?
var avatar: NSURL?
required init?(_ map: Map) { }
func mapping(map: Map) {
self.network <- map["network"]
self.token <- map["token"]
self.avatar <- (map["avatar"], URLTransform())
}
}
Usage:
Alamofire.request(.GET, url)
.responseObject { (response: Response) in
let user = response.result.value
// Get the url to the user's avatar
let avatarURL = user?.accounts?.identities?.first?.avatar
}
If you want to avoid all those ?
, simply give your properties a default value. Of course, this makes sense only if the property is guaranteed to be present in your JSON:
class User: Mappable {
var id = ""
var username = ""
var accounts = UserAccount()
var followers = 0
var following = 0
...
}
How to deserialize json with nested Dictionaries?
I've found a solution for a similar question over here:
Json.NET: Deserializing nested dictionaries.
It uses a custom JsonConverter and I don't see a way to do without it.
how to parse following JSON using object mapper
Your data type is wrong. You need to give "DoctorAvailablityResponseData", but you gave ResponseDoctorAvailablity for mapping.
let user = Mapper<ResponseDoctorAvailablity>().map(response.result.value)
Example
class Doctor: Mappable {
var startDateHour : String?
var callDuration : String?
var endDateHour : String?
required init?(_ map: Map){
}
func mapping(map: Map) {
callDuration <- map["call_duration"]
endDateHour <- map["end_hour"]
startDateHour <- map["start_hour"]
}
}
// Sample Response
let response : NSMutableDictionary = NSMutableDictionary.init(object: "08:00:00", forKey: "start_hour");
response.setValue("10:00:00", forKey: "end_hour");
response.setValue("30", forKey: "call_duration");
// Convert response result to dictionary type. It is very easy.
let userdic = Mapper<Doctor>().map(response) // Map to correct datatype.
NSLog((userdic?.callDuration)!);
// If you result is nested object. you will easily get zero index position object and parse it.
let nestedObjectArray :NSArray = NSArray.init(array: [response]);
let userArray = Mapper().map(nestedObjectArray[0])
NSLog((userArray?.callDuration)!);
Related Topics
Store [String] in Nsuserdefaults
Uigraphicsgetimagefromcurrentimagecontext Memory Leak with Previews
How to Fix Xcode "Dtassetproviderservice Could Not Start.." Error
Custom Annotation View for Userlocation Not Moving the Mapview
Strange Generic Function Appear in View Controller After Converting to Swift 3
Is Nstimer Expected to Fire When App Is Backgrounded
iOS 9 Facebook Login Simulator -Canopenurl: Failed for Url: "Fbauth2:///" - Error: "(Null)"
Retrieve All Contacts Phone Numbers in iOS
iOS Uinavigationbar Button Remains Faded After Segue Back
Force Landscape Orientation in Uiimagepickercontroller
Getting the Word Touched in a Uilabel/Uitextview
Why Are Didbegincontact Called Multiple Times
Passing Image to Another View Controller (Swift)