1

我遇到了一个问题!

我有一个带有 JSON 的字符串,例如:

{"用户名":"用户名","密码":"密码"}

我用 xcode 构建这个 JSON 字符串,如:

 NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
     [jsonDict setValue:self.usernameField.text forKey:@"UserName"];
     [jsonDict setValue:self.passwordField.text forKey:@"PassWord"];
     NSLog(@"Dict: %@",jsonDict);

     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:nil];
     NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
     NSLog(@"JSON String: %@",jsonString);

     NSString *postStr = [NSString stringWithFormat:@"%@",jsonString];

但现在我想要一个带有 JSON 的字符串,例如:

{ "comp": [
  { "id": "1" },
  { "id": "2" },
  { "id": "3" }
 ],
"contact": [
  { "mail": "some@email.com", "name": "Name"  },
  { "mail": "email@email.com", "name": "Name"  }
 ]
}

但是我该怎么做呢?有人可以帮帮我吗?

4

1 回答 1

1

这会给你补偿。使用你所拥有的和这个例子,你应该能够很容易地取得联系。

NSDictionary *id1 = [NSDictionary dictionaryWithObjectsAndKeys:
                       @"1", "id", nil];
NSDictionary *id2 = [NSDictionary dictionaryWithObjectsAndKeys:
                       @"2", "id", nil];
NSDictionary *id3 = [NSDictionary dictionaryWithObjectsAndKeys:
                       @"3", "id", nil];

NSArray *ids = [NSArray arrayWithObjects:id1, id2, id3, nil];

NSDictionary *comp = [NSDictionary dictionaryWithObjectsAndKeys:ids, @"comp", nil];

此外,请查看以下库以轻松进行序列化/反序列化。 JSONKit

于 2012-05-23T15:17:08.913 回答