来自Json的Break String

时间:2013-05-01 02:13:31

标签: iphone ios objective-c json

我有一个来自网络服务器的字符串,它以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"}]

3 个答案:

答案 0 :(得分:8)

你做错了。它是NSArray NSDictionaries。首先,您需要将其分配给NSArray,然后循环遍历它以获取每个NSDictionary。见下文。

NSArray *results = [returnString JSONValue];
for(NSDictionary *record in results)
{
    NSLog(@"ID: %@", [record objectForKey:@"ID"]);
}

答案 1 :(得分:1)

如果您的应用针对iOS 5.0或更高版本

,那么使用NSJSONSerialization 可能会更好。
NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&error];

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

答案 2 :(得分: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];
    }