Reputation: 6723
I have custom object, that contains json. If I print it, it looks like
{
"first_name" = Name;
id = 111111;
"last_name" = LastName;
"photo_100" = "https://url.jpg";
}
This object has property .json. To extract data from it in objective-C I use
NSLog(@"id%@", [[response.json firstObject] objectForKey:@"id"]);
But in Swift, if I try
var dict = response.json
self.name = dict.firstObject.objectForKey("first_name")
self.lastName = dict.firstObject.objectForKey("last_name")
self.photoUrl = dict.firstObject.objectForKey("photo_100")
I get compile or runtime error. I tried call firstObject in dict declaration and and tried downcasting to string - everything leads to errors.
How to extract data correctly ?
UPD: object definition
@interface VKResponse : VKObject
/// Request which caused response
@property(nonatomic, weak) VKRequest *request;
/// Json content of response. Can be array or object.
@property(nonatomic, strong) id json;
/// Model parsed from response
@property(nonatomic, strong) id parsedModel;
/// Original response string from server
@property(nonatomic, copy) NSString *responseString;
@end
Upvotes: 0
Views: 895
Reputation: 20006
First make sure what kind of object you have.
if let jsonDict = json as? [String:AnyObject] {
}
if let jsonArray = json as? [AnyObject]{
}
Upvotes: 0
Reputation: 131426
Based on the code you posted your custom object doesn't contain JSON, it contains objects that were created from JSON. As @TheEye pointed out in their answer, your objective C code suggests that what you have is an array of dictionaries.
Swift is more strictly typed than Objective-C. By default dictionaries and arrays are homogeneous: Dictionaries can only contain key/value pairs where the type of the key is always the same and the type of the value is always the same.
Likewise Swift Arrays are normally typed so that they must contain all the same type of object.
You can create Swift Dictionaries or Arrays that contain generic objects ([AnyObject: AnyObject]
for a dictionary or [Anyobject]
for an array).
Post the definition of your custom object and it's json
property. We need to know how it's declared in order to figure out exactly what you need to do to fix your problem.
Upvotes: 1
Reputation: 9346
If you can write [response.json firstObject]
in Objective C, then response.json is not a dictionary, but an array.
In your Swift code you cast it to a dictionary, which clearly won't work.
Upvotes: 1