开发者

Reading JSON array

I am working on iphone app. Here I am reading an JSON array I have get its values into array the values I get in the following format :

Array : {
global =     {
    players =         {
        1开发者_C百科 = "John Doe, A school";
        10 = "Jonathan Doe, Another school";
        2 = "Joe Doe, Another school";
        3 = "Jane Doe, A school";
        4 = "Jay Doe, Another school";
        5 = "Jimmy Doe, A school";
        6 = "Jeremy Doe, Another school";
        7 = "Johnny Doe, A school";
        8 = "Jeremiah Doe, Another school";
        9 = "Jennifer Doe, A school";
    };
    schools =         {
        1 = "A school";
        2 = "Another school";
        3 = "The school";
        4 = "The other school";
        5 = "That school";
    };
    text = "A dynamic text that needs to be displayed to the player.";
};

Now my problem is that How can I read each part of global? after reading that How can I read schools ? etc...


Look at this question Comparison of JSON Parser for Objective-C (JSON Framework, YAJL, TouchJSON, etc)

It has a list of almost every major JSON parser out there. A JSON parser would convert the JSON to an array/dictionary and let you use objectForKey and objectAtIndex methods to access the structure.


use JSONKit. its the newer and better version of SBJson


Use TouchJSON. It's very easy to use and has a comprehensive documentation.


SBJson is another good Objective-C JSON library. It will parse the JSON into nested NSArray and NSDictionary objects. Canonical usage would be something like:

#import "SBJson.h"

NSString *jsonString = @"{
    'name': 'Simon', 
    'address': {'street': '1 High Street', 'town': 'Anytown'}
}";
NSDictionary *jsonData = [jsonString JSONValue];

NSLog(@"Simon lives in %@", [jsonData valueForKeyPath:@"address.town"]);

Output:

Simon lives in Anytown

As an aside, rather than using dictionaries (denoted by the curly brackets and key:value data form), if you want a list of ordered data (e.g. players in your example) you can just use a list (square brackets enclosing a list of values). So your data becomes:

data: {
    global: {
        players: [
            "John Doe, A school";
            "Joe Doe, Another school";
            "Jane Doe, A school";
            "Jay Doe, Another school";
            "Jimmy Doe, A school";
            "Jeremy Doe, Another school";
            "Johnny Doe, A school";
            "Jeremiah Doe, Another school";
            "Jennifer Doe, A school";
            "Jonathan Doe, Another school";
        ]
        schools: [
            "A school";
            "Another school";
            "The school";
            "The other school";
            "That school";
        ],
        text: "A dynamic text that needs to be displayed to the player.";
    }
};


Just do this

for (var i in global ) {
  for(var j in global [i].schools ){
    alert(global [i].schools[j]);
  }                   
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜