【问题标题】:How to generate JSON programmatically using JSON framework for iPhone如何使用 iPhone 的 JSON 框架以编程方式生成 JSON
【发布时间】:2011-05-18 04:12:16
【问题描述】:

我正在创建一个应用程序,我需要将 JSON 发送到服务器以获得一些响应。

如何使用JSON Framework 为 iPhone 生成 JSON?

还有哪些其他可能的方法?

【问题讨论】:

    标签: ios objective-c json ios4 iphone-sdk-3.0


    【解决方案1】:

    创建一个对象数组或字典,表示您希望通过 JSON 发送的信息。完成后,将-JSONRepresentation 发送到数组/字典。该方法返回一个 JSON 字符串,然后您将其发送到服务器。

    例如:

    NSDictionary *o1 = [NSDictionary dictionaryWithObjectsAndKeys:
        @"some value", @"key1",
        @"another value", @"key2",
        nil];
    
    NSDictionary *o2 = [NSDictionary dictionaryWithObjectsAndKeys:
        @"yet another value", @"key1",
        @"some other value", @"key2",
        nil];
    
    NSArray *array = [NSArray arrayWithObjects:o1, o2, nil];
    
    NSString *jsonString = [array JSONRepresentation];
    
    // send jsonString to the server
    

    执行上述代码后,jsonString 包含:

    [
        {
            "key1": "some value",
            "key2": "another value"
        },
        {
            "key1": "yet another value",
            "key2": "some other value"
        }
    ]
    

    【讨论】:

      【解决方案2】:

      创建一个 NSMutableDictionary 或 NSMutableArray 并用 NSNumbers 和 NSStrings 填充它。调用[<myObject> JSONRepresentation]返回一个JSON字符串。

      例如:

      NSMutableDictionary *dict = [NSMutableDictionary dictionary];
      [dict setObject:@"Sam" forKey:@"name"];
      [dict setObject:[NSNumber numberWithInt:50000] forKey:@"reputation"];
      NSString *jsonString = [dict JSONRepresentation];
      

      【讨论】:

        猜你喜欢
        • 2015-07-29
        • 2020-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多