-1

我有一个从网络服务器获得的字符串,它以 json 格式出现,但字符串很大,其中包含所有内容。我尝试使用 NSDICTIONARY 但没有成功。我想知道打破这个字符串并添加到不同的字符串并最终将它们全部放入一个字符串类中的最佳方法是什么。谢谢您的帮助!这是我的代码:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:@"http://mym2webdesign.com/meiplay/paulsuckedabuffalo/artists.php"]];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSError *error=nil;

NSLog(@"HHHHHHHHHHHHHH"); //use this to know how far Im getting
NSLog(returnString); // Look at the console and you can see what the restults are

/*NSDictionary *results = [returnString JSONValue];
NSString *ID = [results objectForKey:@"ID"]; // for example
NSLog(@"ID Number: %@", ID);*/

这是我得到的一些日志:

[{"ID":"1","name":"kevin","bio":"kevins bio"},{"ID":"1","name":"kevin","age":"20"},{"ID":"2","name":"Cesar","bio":"Cesar bio"},{"ID":"2","name":"Cesar","age":"19"},{"ID":"3", "name":"Katherine", "bio":"Katherines bio"},{"ID":"3", "name":"Katherine", "age":"22"}]
4

3 回答 3

8

你这样做是不对的。它的NSArray一个NSDictionaries。因此,首先您需要将其分配给NSArray然后遍历它以获取每个单独NSDictionary的 . 见下文。

NSArray *results = [returnString JSONValue];
for(NSDictionary *record in results)
{
    NSLog(@"ID: %@", [record objectForKey:@"ID"]);
}
于 2013-05-01T02:20:39.810 回答
1

NSJSONSerialization 如果您的应用程序针对 iOS 5.0 或更高版本,您可能会更好地使用:

NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&error];

您可能需要尝试使用 NSArray 与 NSDictionary 等,但这应该是一个整体更简单的解决方案。

于 2013-05-01T03:05:23.807 回答
1

尝试这个 :

    NSArray *results = [returnString JSONValue];
    for (int i=0; i<[results count];i++) {
       NSDictionary *DetailDictonary=[results objectAtIndex:i];
       NSString *strid=[DetailDictonary objectForKey:@"ID"];
       NSString *strName=[DetailDictonary objectForKey:@"name"]; 
       NSString *strBio=[DetailDictonary objectForKey:@"bio"]; 

        // Or You can set it in Your ClassFile

       MyClass *classObj=[[MyClass alloc] init];
       classObj.strid=[DetailDictonary objectForKey:@"ID"];
       classObj.strName=[DetailDictonary objectForKey:@"name"]; 
       classObj.strBio=[DetailDictonary objectForKey:@"bio"]; 

       [YourMainArray addObject:classObj]; //set YourClass to Array
       [classObj release];
    }
于 2013-05-01T06:01:37.027 回答