【问题标题】:Send NSMutableArray as JSON using JSON-Framework使用 JSON-Framework 将 NSMutableArray 作为 JSON 发送
【发布时间】:2010-07-14 10:20:58
【问题描述】:

我在我的项目中成功使用 JSON-Framework 来解码从服务器发送的 JSON。

现在我需要反过来做,但我遇到了问题,因为要发送的数据是从 CoreData 获取的 NSMutableArray。

使用时

NSString* jsonString = [menuItems JSONRepresentation]

我收到消息“MenuItems 不支持 JSON 序列化”。

我是否需要将 NSMutableArray 转换为其他格式,以便 JSON-Framework 可以对其进行序列化?

感谢您的帮助,
米格尔

【问题讨论】:

    标签: iphone json nsmutablearray json-framework


    【解决方案1】:

    请允许我提出一个更好的解决方案:

    在您的 MenuItems 类中,实现 -proxyForJson 方法,然后您应该能够直接在 menuItems 数组上调用 -JSONRepresentation 方法。

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

    希望这会有所帮助!

    【讨论】:

    • 嗨,Stig,我还没有时间测试它...我一有空就会告诉你。
    【解决方案2】:

    我终于解决了,但我不确定这是否是最好/最优雅的方法。

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

    说明:
    我一开始以为问题出在 NSMutableArray 上,但后来意识到问题出在它的内容上。所以我只是从中获取我需要的信息并将其保存为 JSON-Framework 接受的 NSArray :-)

    【讨论】:

      【解决方案3】:

      这是将字典和数组发送到服务器的示例。它对我有用 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];
      
      }
      

      【讨论】:

      • SBJSON 类来自 oooold 版本。请升级您的 SBJson 副本!
      猜你喜欢
      • 2012-02-28
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      相关资源
      最近更新 更多