草庐IT

ios - JSON 解析 UITableViewController

coder 2024-01-19 原文

我正在尝试将我的 JSON 数据传递到 UITableViewController。我确实设法将我的一个 JSON 传递到 UITableView 并在用户执行操作时将其显示在下一个 ViewController 上。问题是我得到了 4 个 JSON 数据,我希望它显示在 ViewController 上。由于我的 JSON 格式,我无法执行 ObjectForKey。

这是我的 JSON

{
    uid: "60",
    name: "pae1344",
    mail: "viper1344@gmail.com",
    theme: "",
    signature: "",
    signature_format: "plain_text",
    created: "1396189622",
    access: "0",
    login: "1396189622",
    status: "1",
    timezone: "Asia/Bangkok",
    language: "",
    picture: "0",
    init: "viper1344@gmail.com",
    data: null,
    uri: "http://localhost/drupal/rest/user/60"
},

这是来自 myTableViewController 的代码。

#import "TestinViewController.h"
#import "AFNetworking.h"
#import "TestinCell.h"
#import "EDscriptionViewController.h"
@interface TestinViewController ()

@end

@implementation TestinViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.finishedGooglePlacesArray = [[NSArray alloc] init];
    [self makeRestuarantsRequests];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)makeRestuarantsRequests
{
    NSURL *url = [NSURL URLWithString:@"http://localhost/drupal/rest/enterpriselist.json"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation
                                         JSONRequestOperationWithRequest:request
                                         success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject)
                                         {

                                             self.googlePlacesArrayFromAFNetworking = [responseObject valueForKey:@"node_title"];
                                             self.body = [responseObject valueForKey:@"Body"];
                                             self.tel = [responseObject valueForKey:@"Enterprise Tel"];
                                             self.mail = [responseObject valueForKey:@"Enterprise email"];

                                              [self.tableView reloadData];
                                             NSLog(@"%@", self.googlePlacesArrayFromAFNetworking);
                                             NSLog(@"%@" , self.body);
                                             NSLog(@"%@", self.tel);
                                             NSLog(@"%@", self.mail);
                                         }
                                         failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject)
                                         {
                                             NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
                                         }];

    [operation start];

}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [self.googlePlacesArrayFromAFNetworking count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    TestinCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell ==Nil){
        cell = [[TestinCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.txtEnterPriseName.text = [self.googlePlacesArrayFromAFNetworking objectAtIndex:indexPath.row];
    cell.txtEnterPriseBody.text = [self.body objectAtIndex:indexPath.row];
    cell.txtEnterPriseEmail.text = [self.mail objectAtIndex:indexPath.row];
    cell.txtEnterPriseTel.text = [self.tel objectAtIndex:indexPath.row];
    // Configure the cell...

    return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

        NSIndexPath * indexPath = [self.tableView indexPathForSelectedRow];
        EDscriptionViewController *destViewController = (EDscriptionViewController*) segue.destinationViewController ;
        //     destViewController.enterprise = [enterPrise_names objectAtIndex:indexPath.row];
        destViewController.detail = [self.googlePlacesArrayFromAFNetworking objectAtIndex:indexPath.row];


    destViewController.Ebody = [self.body objectAtIndex:indexPath.row];
    destViewController.EEmail = [self.mail objectAtIndex:indexPath.row];
    destViewController.ETel = [self.tel objectAtIndex:indexPath.row];
    //    destViewController.ebody = [self.body objectAtIndex:indexPath.row];
//    destViewController.etel = [self.tel objectAtIndex:indexPath.row];
//    destViewController.email = [self.mail objectAtIndex:indexPath.row];
//    


}

有没有办法让我将 JSON 变成一个字典,这样我就可以使用 ObjectForKey 选择要显示的内容?

最佳答案

首先通过将 .m 和 .h 文件添加到您的项目来使用此库:

JSONKit

然后你可以将 JSON 字符串转换成字典。

//JSONString is a NSString variable with the JSON
NSDictionary *myJSONDic = [JSONString objectFromJSONString]
NSLog(@"User Id is : %@",[myJSONDic valueForKey:@"uid"]);

关于ios - JSON 解析 UITableViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22755762/

有关ios - JSON 解析 UITableViewController的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  4. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  5. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  6. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  7. ruby-on-rails - 我更新了 ruby​​ gems,现在到处都收到解析树错误和弃用警告! - 2

    简而言之错误:NOTE:Gem::SourceIndex#add_specisdeprecated,useSpecification.add_spec.Itwillberemovedonorafter2011-11-01.Gem::SourceIndex#add_speccalledfrom/opt/local/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:91./opt/local/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails/gem_dependency.rb:275:in`==':und

  8. ruby-on-rails - 如何使用 Rack 接收 JSON 对象 - 2

    我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":

  9. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  10. ruby - 用 YAML.load 解析 json 安全吗? - 2

    我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("

随机推荐