Send NSMutableArray as JSON using JSON-Framework

I successfully use the JSON-Framework in my project to decode sending JSON from the server.

Now I need to do it the other way around, and I ran into problems as the data being sent is NSMutableArray extracted from CoreData.

Using

NSString* jsonString = [menuItems JSONRepresentation] 

I get the message "JSON serialization is not supported for MenuItems".

Does NSMutableArray need to be converted to another format so that the JSON-Framework can serialize it?

Thanks for any help
Miguel

+4
source share
3 answers

I finally decided this, but I'm not sure if this is the best / most elegant way to do it.

 NSMutableArray* items = [[NSMutableArray alloc] init]; for (MenuItems* item in menuItems) { [items addObject:[NSArray arrayWithObjects:item.id,[item.modified description],nil]]; } NSString *post = [NSString stringWithFormat:@"currentData=%@", [items JSONRepresentation]]; 

Explanation:
At first I thought that the problem was in NSMutableArray, but then I realized that it was its contents. So I just get the necessary information and save it as an NSArray, which the JSON-Framework accepts :-)

+1
source

Let me suggest a slightly more pleasant solution:

In your MenuItems class, implement the -proxyForJson method, and you should then call the -JSONRepresentation method directly in the menuItems array.

 @interface MenuItems(SBJson) -(id)proxyForJson { return [NSDictionary dictionaryWithObjectsAndKeys: self.id,@"id", [self.modified description],@"modified", nil]; } @end 

Hope this helps!

+4
source

This is an example of sending a dictionary and an array to a server. He worked for me 1,000,000%.

 SBJSON *jparser = [[SBJSON new] autorelease]; NSString *ArrayjsonItems = [jparser stringWithObject:self.UrMergedArray]; NSString *DicjsonItems = [jparser stringWithObject:self.UrMergedDic]; NSLog(@"array Items :%@",self.UrMergedArray); NSLog(@"dic Items :%@",self.UrMergedDic); NSString *postString =[NSString stringWithFormat:@"Arrayitems=%@&Dicitems=%@",ArrayjsonItems,DicjsonItems]; NSLog(@"it is going to post : %@ \n\n",postString); NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:snapURL]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection) { self.receivedData = [[NSMutableData alloc]init]; } 
0
source

Source: https://habr.com/ru/post/1315641/


All Articles