I get data from a request that has the next structure:
description
idd
name
url
photo
"result" from the NSDictionary stores info, this is the method I use.
-(void)loadLinks{
NSDictionary *dictToSend = #{#"controller": #"link",
#"action": #"loadall"
};
[ApiCaller sendDictionary: dictToSend
toURL: nil
withKey: nil
completionHandler: ^(NSDictionary *result, NSError *error) {
if (!error) {
[CommonFunctions desActivateIndicator];
DCArrayMapping *mapper = [DCArrayMapping mapperForClassElements:[JSONLink class] forAttribute:#"data" onClass:[JSONLinks class]];
DCParserConfiguration *config = [DCParserConfiguration configuration];
[config addArrayMapper:mapper];
DCKeyValueObjectMapping *parser = [DCKeyValueObjectMapping mapperForClass:[JSONLinks class] andConfiguration:config];
linksData = [parser parseDictionary: result];
[tableview reloadData];
}
}];
}
I'm using this to fill a tableview with some links. The error is the next.
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<JSONLink 0x7fc7f0c759b0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key description.'
My JSONLinks.h file:
#import <Foundation/Foundation.h>
#interface JSONLinks : NSObject
#property (nonatomic, strong) NSNumber *success;
#property (nonatomic, strong) NSArray *data;
#end
My JSONLink.h file:
#import <Foundation/Foundation.h>
#interface JSONLink : NSObject
#property (nonatomic, strong) NSNumber *idd;
#property (nonatomic, copy) NSString *name;
#property (nonatomic, copy) NSString *url;
#property (nonatomic, copy) NSString *descriptionData;
#property (nonatomic, copy) NSString *photo;
-(NSString *) urlDirection;
#end
Where is the error? :S
Thank you.
Related
I'm running into some trouble with a PFObject subclass. I've gone thru all of the proper setup (registering the subclass in the delegate, setting the class name, etc). But for some reason I can't get the object to load without crashing it in the view that it's supposed to be loading in.
Passing the Object
if ([segue.identifier isEqualToString:#"toPostView"])
{
pbPostViewController *postView = [pbPostViewController new];
postView = (pbPostViewController *)segue.destinationViewController;
[postView setPostToLoad:_selectedPost];
}
Receiving View.h
// Copyright (c) 2015 Chris Culos. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "PALongTextView.h"
#import "pbPost.h"
#interface pbPostViewController : UIViewController
#property (strong, nonatomic) pbPost *postToLoad;
Receiving View.m
#import "pbPost.h"
#interface pbPostViewController ()
#end
#implementation pbPostViewController
- (void)viewDidLoad {
pbPost *post = [pbPost postWithObject:_objectToLoad];
NSLog(#"post: %#", post);
// _timeStampLabel.text = post.postTimeStamp;
_userNameLabel.text = [post.postOwner valueForKey:#"username"];
_profileImage.image = [post.postOwner valueForKey:#"profileImage"];
_postDescriptionView.text = post.postDescriptionString;
_bookmarkCounterLabel.text= [NSString stringWithFormat:#"%li bookmarks", post.postBookmarkedArray.count];
_postContentView.text = #"POST CONTENT PAGE 123 456 ETC ETC ETC";
[super viewDidLoad];
//
pbPost.h
#interface pbPost : PFObject <PFSubclassing>
{
}
#property (nonatomic, retain) NSDate *postTimeStamp;
#property (nonatomic, retain) NSString *postDescriptionString;
#property (nonatomic, retain) NSString *postContentString;
#property (nonatomic, retain) NSString *postBookmarkString;
#property (nonatomic, retain) NSString *postPageCounterString;
#property (nonatomic, retain) NSArray *postBookmarkedArray;
#property (nonatomic, retain) PFFile *postOwnerProfileImage;
#property (nonatomic, retain) NSNumber *postFontSize, *totalPages;
#property (nonatomic, retain) PFUser *postOwner;
+ (pbPost *) postWithObject: (PFObject *)object;
pbPost.m
#implementation pbPost
#dynamic postContentString, postBookmarkString, postDescriptionString, postPageCounterString, postTimeStamp, commentTableView, commentButton, bookMarkButton, postOwnerProfileImage, optionsButton, postFontSize, totalPages, postBookmarkedArray, postOwner;
+ (void)load
{
[self registerSubclass];
}
+ (NSString *)parseClassName
{
return #"userPosts";
}
+ (pbPost *) postWithObject: (PFObject *)object
{
// NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// [dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
// [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
pbPost *post = [pbPost postWithObject:object];
[post fetchInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (!error) {
post.postTimeStamp = [object valueForKey:#"createdAt"];
post.postDescriptionString = [object valueForKey:#"titleSummary"];
post.postFontSize = [object valueForKey:#"fontSize"];
post.postContentString = [object valueForKey:#"postContent"];
post.totalPages = [object valueForKey:#"numPages"];
post.postBookmarkedArray = [object valueForKey:#"bookmarkedBy"];
post.postOwner = [object valueForKey:#"postOwner"];
post.postOwnerProfileImage = [post.postOwner valueForKey:#"profileImage"];
NSLog(#"LOAD THE THING!: %#", post);
}
else
{
NSLog(#"Error Loading Post: %#", error);
}
}];
return post;
}
Under this circumstance; I'm getting an EXC_BAD_ACCESS at + (pbPost *)postWithObject:(PFObject *)object in the implementation file.
I feel like I'm missing something very simple here; what can it be? Thanks in advance for your help again everyone! This has stumped me for a little while and I need to get some outside help.
Since you're passing the pbPost object, you don't need to call the + (pbPost *)postWithObject:(PFObject *)object at all. To create a new instance of your PFObject subclass, you can just call:
pbPost *post = [pbPost object];
I am attempting to use this JSONModel library in an app I'm building. I've been following this article, but for some reason I keep getting (null) when attempting to parse the json string. I was told that it is because I'm not creating a json instance; but it seems to me I am. Below is the code, can anyone see what I'm missing? I'm attempting to use this web service, with these inputs:
emailAddress: wufpakjack#yahoo.com;
password: test;
companyId: 2579;
scheduleDate: 20140415.
myShiftModel.h
#import "JSONModel.h"
#interface myShiftModel : JSONModel
#property (assign, nonatomic) NSString *shiftName;
#property (assign, nonatomic) NSString *shiftStartTime;
#property (assign, nonatomic) NSString *shiftPosition;
#end
dailyViewModel.h
#import "JSONModel.h"
#import "myShiftModel.h"
#protocol dailyViewModel #end
#interface dailyViewModel : JSONModel
#property (assign, nonatomic) int numAvailableXChanges;
#property (strong, nonatomic) NSString *todaysForecast;
#property (assign, nonatomic) int todaysTemperature;
#property (strong, nonatomic) myShiftModel *workShift;
#end
dailyFeed.h
#import "JSONModel.h"
#import "dailyViewModel.h"
#interface dailyFeed : JSONModel
#property (strong, nonatomic) NSArray <dailyViewModel> *workShifts;
#end
mainViewController.m
#import "mainViewController.h"
#import "JSONModelLib.h"
#import "JSONModel+networking.h"
#import "dailyFeed.h"
#interface mainViewController () {
dailyFeed *feed;
}
#end
#implementation mainViewController
- (void)viewDidAppear:(BOOL)animated {
NSString *email = [[NSString alloc]initWithFormat:#"wufpakjack#yahoo.com"];
NSString *pass = [[NSString alloc]initWithFormat:#"test"];
NSString *compID = [[NSString alloc]initWithFormat:#"2579"];
NSString *date = [[NSString alloc]initWithFormat:#"20140415"];
NSString *urlString = [NSString stringWithFormat:#"http://qa.shiftzen.com/ws/schedutils.asmx/GetDailyView?emailAddress=%#&password=%#&companyId=%#&scheduleDate=%#", email,pass,compID,date];
NSLog(#"%#", urlString);
[JSONHTTPClient getJSONFromURLWithString:urlString
completion:^(NSDictionary *json, JSONModelError *err) {
NSError* error = nil;
feed = [[dailyFeed alloc] initWithDictionary:json error:&error];
NSLog(#"shifts: %#", feed.workShifts);
}];
}
#end
Any guidance would be greatly appreciated.
Warmest regards,
DB
This is Apprecord class
#interface AppRecord : NSObject
#property (nonatomic, strong) NSString *appIcon;
#property (nonatomic, strong) NSString * name;
#property (nonatomic, strong) NSString * description;
#property (nonatomic, strong) NSString * location;
#property (nonatomic, strong) NSString * address;
#property (nonatomic, strong) NSString * contacts;
#property (nonatomic, strong) NSString * additional_info;
#property (nonatomic, strong) NSString * image;
#end
and I am parsing json adding to an object of App record class
#import "ParserClass.h"
#import "AppRecord.h"
#interface ParserClass ()
#property (nonatomic, strong) NSArray *appRecordList;
#property (nonatomic, strong) NSData *dataToParse;
#property (nonatomic, strong) NSMutableArray *workingArray;
#property (nonatomic, strong) AppRecord *workingEntry;
#property (nonatomic, strong) NSMutableString *workingPropertyString;
#property (nonatomic, strong) NSArray *elementsToParse;
#property (nonatomic, readwrite) BOOL storingCharacterData;
#end
#implementation ParserClass
- (id)initWithData:(NSData *)data
{
self = [super init];
if (self != nil)
{
_dataToParse = data;
}
return self;
}
- (void)main
{
self.workingArray = [NSMutableArray array];
self.workingPropertyString = [NSMutableString string];
self.workingArray=[[NSMutableArray alloc]init];
NSDictionary *allData=[NSJSONSerialization JSONObjectWithData:_dataToParse options:0 error:nil];
NSLog(#"%#",allData);
for (NSDictionary *dict in allData)
{
NSLog(#"dict====%#",dict);
self.workingEntry=[[AppRecord alloc]init];
self.workingEntry.name=[dict objectForKey:#"name"];
self.workingEntry.description=[dict objectForKey:#"description"];
self.workingEntry.location=[dict objectForKey:#"location"];
self.workingEntry.address=[dict objectForKey:#"address"];
self.workingEntry.contacts=[dict objectForKey:#"contacts"];
self.workingEntry.additional_info=[dict objectForKey:#"additional_info"];
self.workingEntry.image=[dict objectForKey:#"image"];
[self.workingArray addObject:self.workingEntry];
}
NSLog(#"WORKING ARRAY========%#",self.workingArray);// Not getting proper value of working array
self.workingArray = nil;
self.workingPropertyString = nil;
self.dataToParse = nil;
}
#end
My problem is not getting proper value of working array,it only stores description property,but it should store apprecord object,please help.
OUTPUT
alldata=
(
{
"additional_info" = "lOREN iPSUM";
address = "1972 Hillview St. Sarasota,FL 34239";
contacts = 8745674556;
description = "Very cute place, awesome wait staff, great food. I am here on vacation and it was an awesome place to go to after a day relaxing at the beach.";
id = 1;
image = "http://..";
location = "1972 Hillview St. Sarasota,FL 34239";
name = "Beer Tasting at Hurricane Hanks";
},
{
"additional_info" = gdfgdfg;
address = "Farrer Place, Sydney, New South Wales, Australia";
contacts = 3423423423423;
description = restataurant;
id = 16;
image = "http://..";
location = kolkata;
name = "mosco ";
}
)
WORKING ARRAY========(
"Very cute place, awesome wait staff, great food. I am here on vacation and it was an awesome place to go to after a day relaxing at the beach.",
restataurant
)
First object name== Beer Tasting at Hurricane Hanks
First you remove 2 time intialization of self.workingArray
And please replace
#property (nonatomic, strong) NSString * description;
deccription with some other name
To know the reason click this link
for (NSDictionary *dict in allData)
{
AppRecord *createAppRecord=[[AppRecord alloc]init];
//Do some thing
[self.workingArray addObject:createAppRecord];
}
I think it will be helpful to you.
I'm trying to serialize my Cart object which has an NSMutableArray of items in it but getting an:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Item)'
If I'm understanding how this is supposed to work, I need to create an Array of Dictionaries in order for NSJSONSerialization to work correctly. Is that not what I am doing below?
My Cart.h:
#interface Cart : BaseObject
#property (nonatomic, strong) NSString *comp;
#property (nonatomic, strong) NSString *sono;
#property (nonatomic, strong) NSString *cust;
#property (nonatomic, strong) NSString *scus;
#property (nonatomic, strong) NSString *cnid;
#property (nonatomic, strong) NSString *dldt;
#property (nonatomic, strong) NSString *whse;
#property (nonatomic, strong) NSString *pono;
#property (nonatomic, strong) NSString *pon2;
#property (nonatomic, strong) NSString *emad;
#property (nonatomic, strong) NSString *pkin;
#property (nonatomic, strong) NSString *comt;
#property (nonatomic, strong) NSString *rtin;
#property (nonatomic, strong) NSString *lbfg;
#property (nonatomic, strong) NSString *containsOpenPriced;
#property (nonatomic, strong) NSString *totalProductAmount;
#property (nonatomic, strong) NSMutableArray *items;
#property (nonatomic) BOOL *isSubmitting;
#end
My Cart.m:
#implementation Cart
#synthesize comp;
#synthesize sono;
#synthesize cust;
#synthesize scus;
#synthesize cnid;
#synthesize dldt;
#synthesize whse;
#synthesize pono;
#synthesize pon2;
#synthesize emad;
#synthesize pkin;
#synthesize comt;
#synthesize rtin;
#synthesize lbfg;
#synthesize containsOpenPriced;
#synthesize totalProductAmount;
#synthesize items;
- (id) initWithDictionary:(NSDictionary *)dictionary {
self = [super init];
if (self) {
self.comp = dictionary[#"comp"];
self.sono = dictionary[#"sono"];
self.cust = dictionary[#"cust"];
self.scus = dictionary[#"scus"];
self.cnid = dictionary[#"cnid"];
self.dldt = dictionary[#"dldt"];
self.whse = dictionary[#"whse"];
self.pono = dictionary[#"pono"];
self.pon2 = dictionary[#"pon2"];
self.emad = dictionary[#"emad"];
self.pkin = dictionary[#"pkin"];
self.comt = dictionary[#"comt"];
self.rtin = dictionary[#"rtin"];
self.lbfg = dictionary[#"lbfg"];
self.containsOpenPriced = dictionary[#"containsOpenPriced"];
self.totalProductAmount = dictionary[#"totalProductAmount"];
NSArray *itemsArray = dictionary[#"items"];
NSMutableArray *itemsMutableArray = [[NSMutableArray alloc]init];
for (NSDictionary *itemDictionary in itemsArray) {
Item *item = [[Item alloc] initWithDictionary:itemDictionary];
[itemsMutableArray addObject:item];
}
self.items = itemsMutableArray;
}
return self;
}
#end
My code for serializing my object:
NSMutableArray *itemsToSerialize = [[NSMutableArray alloc] init];
for (Item *item in cart.items) {
NSMutableDictionary *itemDict = [[NSMutableDictionary alloc] init];
[itemDict setObject:item forKey:#"item"];
[itemsToSerialize addObject:item];
}
NSMutableDictionary *data = [#{
#"comp" : cart.comp,
#"rtin" : cart.rtin,
#"pono" : cart.pono,
#"pon2" : cart.pon2,
#"totalProductAmount" : totalProductAmount,
#"sono" : cart.sono,
#"emad" : cart.emad,
#"lbfg" : lbfg,
#"pkin" : cart.pkin,
#"containsOpenPriced" : containsOpenPriced,
#"cnid" : cart.cnid,
#"whse" : cart.whse,
#"scus" : cart.scus,
#"dldt" : cart.dldt,
#"cust" : cart.cust,
#"comt" : cart.comt,
#"items": itemsToSerialize
} mutableCopy];
NSString *command = #"shoppingCart.update";
NSMutableDictionary *request = [#{
#"command" : command,
#"comp" : cart.comp,
#"cnid" : sessionController.operator.cnid,
#"cust" : cart.cust,
#"data" : data
} mutableCopy];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:request options:kNilOptions error:nil];
This dies on the above NSJSONSerialization line. What am I missing?
This line: [itemsToSerialize addObject:item]; should be [itemsToSerialize addObject:itemDict];. The result is that you're trying to serialize an array of the items themselves, which gives the exception you're seeing.
NSJSONSerialization only works on arrays (NSArray or NSMutableArray), dictionaries (NSDictionary or NSMutableDictionary, strings (NSString or NSMutableString), and NSNumber.
The common mechanism is to create a - (NSDictionary *)serialize method on your class that copies all its values into a dictionary to be passed into NSJSONSerialization. Then implement - (id)initFromSerialization:(NSDictionary *)serialization to deserialize the object.
I know this is kinda late but maybe this class can ease your coding:
Its a class that transform Custom NSObject to JSON readable object(NSArray or NSDictionary). Have a try and see. It has the capability to skip properties and changed property type from string to NSInteger or Float, it can also changed the final output property name lets say
CustomObject *X;
X.property1 = #"Test";
//and the output JSON readable format you want tot change X to Y
//CustomObject converted to readable format
{Y = #"Test"}
here is the class Disassembler
I have two classes
=== PEOPLE ====
#protocol People #end
#interface People : JSONModel
#property (strong, nonatomic) NSString *id;
#property (strong, nonatomic) NSString *userName;
#end
=== PEOPLE CONTAINER ====
#interface PeopleContainer : JSONModel
#property (strong, nonatomic) People *people;
#end
The code fails at this line:
PeopleContainer *peopleContainer = [[PeopleContainer alloc] initWithDictionary:peopleContainerDict error:&err];
giving error:
*** Terminating app due to uncaught exception 'Type not allowed', reason: 'Account type not supported for ChatRoomContainer.account'
*** First throw call stack: (0x2243012 0x1725e7e 0x34e90 0x76ef5 0xf18cf8 0xe8075a 0xe4e453 0xe4e164 0xedaa31 0x50fe53f 0x5110014 0x51012e8 0x5101450 0x53d9e72 0x53c1daa) libc++abi.dylib: terminate called throwing an exception
The problem is that it works perfectly fine with iOS >7 but not on iOS 6.1
(I have tested it on both simulator and device).
Can someone help?
EDIT:
Here is the ACCOUNT CLASS
#import <Foundation/Foundation.h>
#import "JSONModel.h"
#protocol Account #end
#interface Account : JSONModel
#property (strong, nonatomic) NSString *id;
#property (strong, nonatomic) NSString *userName;
#property (strong, nonatomic) NSString *emailAddress;
#property (strong, nonatomic) NSString *password;
#property (strong, nonatomic) NSString *phoneNumber;
#end
And the other class CHAT ROOM CONTAINER containing the ACCOUNT CLASS
#import "JSONModel.h"
#import "Account.h"
#import "Friend.h"
#import "ChatRoom.h"
#interface ChatRoomContainer : JSONModel
#property (strong, nonatomic) Account *account;
#property (strong, nonatomic) NSArray<ChatRoom> *chatRooms;
#property (strong, nonatomic) NSArray<Friend> *friends;
#end
I send out a request to our server using
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:
^(NSURLResponse *response, NSData *data, NSError *error)
{
if (completion) {
if (!error) {
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *errorDict = [responseDict objectForKey:#"error"];
NSDictionary *warningDict = [responseDict objectForKey:#"warning"];
NSDictionary *result = [responseDict objectForKey:#"result"];
NSLog(#"RESULT\n====\n%#\n====\n",responseDict);
if(errorDict != nil && ![[NSNull null] isEqual:errorDict]) {
NSError* err = nil;
CustomError *error = [[CustomError alloc] initWithDictionary:errorDict error:&err];
completion(NO, nil, error, nil);
} else {
NSDictionary *chatRoomContainerDict = [result objectForKey:#"chatRoomContainer"];
NSError* err = nil;
ChatRoomContainer *chatRoomContainer = [[ChatRoomContainer alloc] initWithDictionary:chatRoomContainerDict error:&err];
if(!err) {
CustomWarning *warning = [[CustomWarning alloc] initWithDictionary:warningDict error:&err];
completion(!error, chatRoomContainer, nil, warning);
} else {
NSLog(#"ERROR WHILE PARSING CHAT ROOM CONTAINER JSON DICT!!! %#", [err userInfo]);
completion(!error, nil, nil, nil);
}
}
} else {
if(![AuxiliaryHelper connectedToInternet]) {
NSLog(#"NO INTERNET CONNECTION");
completion(NO, nil, [[CustomError alloc] initWithErrorType:ErrorTypeNoInternetConnection], nil);
} else {
DLog(#"INTERNAL SERVER ERROR!!!");
completion(NO, nil, [[CustomError alloc] initWithErrorType:ErrorTypeInternalServerError], nil);
}
}
}
}];
I also encounter this problem. maybe the error came from your class "Account,chatRoom,etc".
I wrote
objc
#property (assign,nonatomic) NSInteger goodId;
into
objc
#property (assign,nonatomic) NSInteger* goodId;
so just check U class