在Objective-C中发布JSON [英] Posting JSON in Objective-C

查看:91
本文介绍了在Objective-C中发布JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天有一个相当容易的问题。我有一个应用程序,需要以2D GPS坐标的形式将一个简单的JSON数组发送到远程服务器。该应用程序将使用CoreLocation框架来生成这些坐标。现在,我想硬编码一些样本坐标以获得正确的JSON。但是,我似乎无法在ObjC代码中正确形成JSON。

I've got a fairly easy question today. I have an app that needs to send a simple JSON array to a remote server in the form of 2D GPS coordinates. The app will use the CoreLocation framework in order to generate these coordinates. For now, I want to hard code some sample coordinates to get the JSON right. However, I cannot seem to form the JSON correctly within the ObjC code.

以下是代码:

NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:myserver/handler/index"]];
[request setHTTPMethod:@"POST"];
NSString *jsonString = @"{"
@"  \"geo\": {"
@"    \"lat\": \"37.78\","
@"    \"lon\": \"-122.40";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[request setHTTPBody:jsonData];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];

以下是服务器的预期(但未收到):

Here is what the server is expecting (but not receiving):

{
"geo": {
    "lat": "37.78",
    "lon": "-122.40"
}

我确定这是一个简单的JSON格式问题,或者是我自己的另一个零钱移动。

I'm sure it's a simple JSON formatting issue or otherwise numskull move on my part.

任何帮助总是受到赞赏!

Any help is always appreciated!

推荐答案

你这样做很难。创建一个 NSDictionary 然后将其转换为所需的JSON数据:

You are doing this the hard way. Create an NSDictionary then convert that to the desired JSON data:

NSDictionary *dictionary = @{ @"geo" : @{ @"lat" : @"37.78", @"lon" : @"-122.40" } };
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
if (jsonData) {
    // process the data
} else {
    NSLog(@"Unable to serialize the data %@: %@", dictionary, error);
}

根本不需要字符串。

编辑:如果您的真实数据是一个对象数组,那么创建一个字典数组或您需要的任何结构。其余的都一样。

If your real data is an array of objects then create an array of dictionaries or whatever structure you need. The rest is the same.

这篇关于在Objective-C中发布JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆