How to generate JSON programmatically using JSON framework for iPhone

为君一笑 提交于 2019-12-03 09:53:44

问题


I am creating an application in that I need to send a JSON to the server to get some response.

How to generate JSON using JSON Framework for iPhone?

What are the other possible ways?


回答1:


Create an array or dictionary of objects representing the information you want to send via JSON. Having done that, send -JSONRepresentation to the array/dictionary. That method returns a JSON string, and you send it to the server.

For instance:

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

After executing the code above, jsonString contains:

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



回答2:


Create an NSMutableDictionary or NSMutableArray and populate it with NSNumbers and NSStrings. Call [<myObject> JSONRepresentation] to return a JSON string.

eg:

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


来源:https://stackoverflow.com/questions/6039780/how-to-generate-json-programmatically-using-json-framework-for-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!