目标C中的JSON对象

时间:2015-02-25 01:22:26

标签: json xcode6 nsmutablearray

我需要在XCode中使用以下格式创建一个json对象,并且我一直在使用XCode 6.

   string json = @"{'user': 'Teva',
                    'password': 'abc123',
                    'SourceID':1,
                    'SiteID':1,
                    'VariableID':1,
                    'MethodID':1,
                    'values':[
                        ['2015-01-29 21:00:00',133.0],
                        ['2015-01-29 22:00:00',134.0]
                    ]}";

我尝试过NSDictonary方法。但是,我得到以下输出: 这是我的代码。

- (void)viewDidLoad {
       [super viewDidLoad];
       NSError *error;
       NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                @"user", @"Teva",
                                @"password", @"abc123",
                                @"SourceID", @"1",
                                @"SiteID", @"1",
                                @"VariableID", @"1",
                                @"MethodID", @"1",
                                @"values", @"[2015-01-29 21:00:00, 134.0], [2015-01-29 22:00:00, 135.0]",
                               nil];


NSMutableArray * arr = [[NSMutableArray alloc] init];

[arr addObject:jsonDictionary];

NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];

NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];

NSLog(@"jsonData as string:\n%@", jsonString);
}

我得到了以下输出:

jsonData as string:
[
 {
   "abc123" : "password",
   "1" : "VariableID",
   "Teva" : "user",
   "[2015-01-29 21:00:00, 134.0], [2015-01-29 22:00:00, 135.0]" :      "values",
  "campaignCategory" : "MethodID",
  "actionDate" : "SiteID",
  "dueDate" : "SourceID"
 }
]

任何人帮助我使用目标C获得正确的json。感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这是我希望得到的答案。我希望它可能对某人有用。

-(void)saveDataValue
{
NSMutableArray *matchArray = [NSMutableArray arrayWithObjects:@"2015-01-29 21:00:00", @(134.0), nil];

NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"Teva" forKey:@"user"];
[contentDictionary setValue:@"abc123" forKey:@"password"];
[contentDictionary setValue:@"1" forKey:@"SourceID"];
[contentDictionary setValue:@"1" forKey:@"SiteID"];
[contentDictionary setValue:@"1" forKey:@"VariableID"];
[contentDictionary setValue:@"1" forKey:@"MethodID"];
[contentDictionary setValue:matchArray forKey:@"values"];
NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"jsonData as string:\n%@", jsonStr);
}

快乐编码...... :)