如何在iOS中的JSON数据数组中在textview中显示字符串数组?

时间:2016-04-18 06:08:21

标签: ios objective-c

这是我用于更新textview文本的代码示例,我想传递来自JSON响应的数组中的所有字符串

- (void)viewDidLoad {
[super viewDidLoad];
NSString *parseURL = @"url link";
NSString *encodeurl =[parseURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodeurl];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data){
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
    NSArray *messageArray = [json objectForKey:@"Branches"];
    for (NSDictionary * dataDict in messageArray) {
        NSString *me = [dataDict objectForKey:@"branch_name"];
        txt.text = me;
    }
}

}

5 个答案:

答案 0 :(得分:0)

首先,您要一次又一次地在textView中设置for loop文字,以替换之前的文字。因此,您必须append单个字符串中的所有字符串,并在for循环结束后将此字符串分配给UITextView.

由于

答案 1 :(得分:0)

正常情况下,它会显示最新的字符串,因为您正在运行循环,此循环中的最新对象会覆盖前一个

您可以在NSMutableString循环

之前使用for
NSMutableString *branchesString = [[NSMutableString alloc] init];

然后进入你的for循环呢

[branchesString appendString:[NSString stringWithFormat:@"%@, ", [dataDict objectForKey:@"branch_name"]]];
循环后,您可以将此字符串设置为textView.text

您的代码看起来像这样

if(data){
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
    NSArray *messageArray = [json objectForKey:@"Branches"];

    NSMutableString *branchesString = [[NSMutableString alloc] init];

    for (NSDictionary * dataDict in messageArray) {
        [branchesString appendString:[NSString stringWithFormat:@"%@ ", [dataDict objectForKey:@"branch_name"]]];
    }

    txt.text = branchesString;

}

答案 2 :(得分:0)

只需改变你的for循环,

  for (NSDictionary * dataDict in messageArray) {

    NSString *me = [dataDict objectForKey:@"branch_name"];

    txt.text = [txt.text stringByAppendingString:me]; //change



    //txt.text =messageArray;

    // Do any additional setup after loading the view, typically from a nib.
}

如果你想要新行中的下一个字符串,那么

 txt.text = [txt.text stringByAppendingString:[NSString stringWithFormat:@"%@\n",txt.text]];

如果想用逗号分隔,那么

 txt.text = [txt.text stringByAppendingString:[NSString stringWithFormat:@"%@,",txt.text]];

希望这会有所帮助:)

答案 3 :(得分:0)

for / for-each循环是多余的。在阵列上使用componentsJoinedByString:

NSArray *messageArray = [json objectForKey:@"Branches"];

txt.text = [messageArray componentsJoinedByString:@"\n"]; // linebreak between each message

// Use a space, comma, linebreak (\n), or whatever separator you prefer.

答案 4 :(得分:0)

NSArray * arrMsg = [json valueForKeyPath:@"Branches.branch_name"];

txt.text = [arrMsg componentsJoinedByString:@"\n"];  //use your saperator which you want to join the strings