Good day. I need help with JSON on iOS. I need to decipher the numbers in the "des" section and put it in the Label . All parsers are too large and complex, there is no simple lesson. = (Help ...

This is all the code of the page to be parsed.

 {"des":1.00,"dem":1085.16,"spo":1.44,"def":0.66,"cap":1.84,"all":11739,"win":53.42,"lvl":6.77,"status":"noerror","name":"_shuzik_"} 

PS Don't kick me hard, I'm new. Honestly, I tried to figure it out = (


If someone needs to use, I found the easiest (For me) option

We add AFNetworking and HTMLParser to the project, you can download it everywhere.

In .h

 @property (nonatomic, strong) IBOutlet UILabel *allLabel; 

I added by need UILabel

In .m

 #import "InfoViewController.h" #import "HTMLParser.h" #import "AFJSONRequestOperation.h" // тут все теги которые нам нужны, можно писать отдельно, можно через заятую в зависимости от того что вам нужно. #define iAll @"all" @interface InfoViewController () @end @implementation InfoViewController @synthesize allLabel = _allLabel; - (void)viewDidLoad { [super viewDidLoad]; NSURL *url = [NSURL URLWithString:@"http://......."]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]]; AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { NSLog(@"JSON %@", JSON); NSDictionary *data = (NSDictionary *)JSON; if (data) { // так как на выходе получаем нс намбер, его нужно завернуть в нс стринг - иначе краш NSString *editAlltext = [NSString stringWithFormat:@"%@", [data objectForKey:iAll]]; self.allLabel.text = editAlltext; } } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){ NSLog (@"Err : %@", error); }]; [operation start]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end 

I work through the XIB, so after that, I went to the XIB and threw a Label on the monitor and connected it to allLabel

I hope I wrote it clearly. Use!

    3 answers 3

    But where are the complex ones, SBJSON only needs to jerk on the incoming JSONValue line, having received an array or a dictionary at the output. And in 6 ayoshi also appeared his own, I really have never used it

    • That's the problem, a lot of files, damn it, what to do with it. Can tutarial on this ??? - Svyatoslav Boyko
    • What exactly is the problem? Pull the source, add to the project, and where you want to use - #import "SBJson.h" and forward - aknew
    • Thanks, I'll try! - Svyatoslav Boyko

    Since there are no labels on the language, I propose an option in Си :

     char des[100]; if( sscanf( pJSON, "{\"des\":%[^,],", &des[0] ) == 1 ){ // в des теперь значение переменной 'des' из буфера pJSON SetLabelText( des ); } 

    If it is possible to use sscanf_s , then it will be preferable. Since only text is needed, I do not suggest parsing des in float , but if necessary I will write. Although, probably for the sake of verifying the value, you can do extra work:

     char des[100]; float fdes; if( sscanf( pJSON, "{\"des\":%f,", &fdes ) == 1 ){ // в fdes теперь значение переменной 'des' из буфера pJSON sprintf( des, "%f", fdes ); SetLabelText( des ); } 
    • Desirable b in Obj-s =) - Svyatoslav Boyko
    • @ Svyatoslav: isn’t obj-c a superset of pure C? - VladD
    • @mega: for JSON, spaces are allowed before / after the colon. And the des field may not be the first. And des it can be a subfield of some other field (for example, spo ): JSON is a recursive thing. So from the handwriting or use of the finished parser does not leave. - VladD
    • > for JSON, spaces are allowed before / after the colon. And the des field may not be the first. And des it can be a subfield of some other @VladD field, here is given a specific JSON , with a specific task, to which I offered a simple answer. If we were talking about some kind of dynamic request, from several servers on which javascript objects would be wrapped by different generators, then I would understand your concern. But if the JSON scheme is static, then a full parser is not needed. - mega
    • @mega: well, this is some kind of dishonest approach. if we assume that the format of the input data never changes, then why not read the substring at all at a fixed offset from the beginning of the line? Your code does not parse a specific JSON, but a specific string. - VladD

    I myself use SBJSON. There are 2 main methods.

    • .- (NSString *) JSONRepresentation; // convert object to json string
    • .- (id) JSONValue; // convert json string to object

       NSString *ourString = @"{\"des\":1.00,\"dem\":1085.16,\"spo\":1.44,\"def\":0.66,\"cap\":1.84,\"all\":11739,\"win\":53.42,\"lvl\":6.77,\"status\":\"noerror\",\"name\":\"_shuzik_\"}"; NSDictionary *jsonDic = [ourString JSONValue]; NSString *jsonString = [jsonDic JSONRepresentation]; NSString *desStriing = [jsonDic valueForKey:@"des"]; 

    Everything is very convenient, Try it. I have enough for comfortable work

    • Json.h
    • NSObject + SBJSON
    • NSString + SBJSON
    • SBJsonBase
    • SBJsonParser
    • SBJsonWriter
    • Thanks, I will try! - Svyatoslav Boyko