Send NSMutableArray as JSON using JSON-Framework

2019-02-24 04:56发布

I'm using JSON-Framework in my project successfully to decode JSON send from a server.

Now I need to do it the other way around and I'm facing problems as the data to be sent is a NSMutableArray fetched from CoreData.

When using

NSString* jsonString = [menuItems JSONRepresentation]

I get the message "JSON serialisation not supported for MenuItems".

Do I need to convert the NSMutableArray to some other format so the JSON-Framework can serialize it?

Thanks for any help,
Miguel

3条回答
一夜七次
2楼-- · 2019-02-24 05:49

I finally solved it, but I'm not sure if it's 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:
I first thought that the problem was the NSMutableArray, but then realized that it was the contents of it. So I just get the information I need out of it and saved it as NSArray which JSON-Framework does accept :-)

查看更多
Explosion°爆炸
3楼-- · 2019-02-24 05:59

Allow me to suggest a somewhat nicer solution:

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

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

Hope this helps!

查看更多
戒情不戒烟
4楼-- · 2019-02-24 05:59

This is an example of sending dictionary and array to server.which worked for me 1000000% .

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];

}
查看更多
登录 后发表回答