开发者

Parsing JSON file using JSONKit

I am constructing a tuning fork app. The fork should allow up to 12 preset pitches.

Moreover, I wish to allow the user to choose a theme. Each theme will load a set of presets (not necessary to use all of them).

My configuration file would look something like this*:


theme: "A3"
comment: "An octave below concert pitch (ie A4 440Hz)"
presets: {
    A3 220Hz=220.0
}

// http://en.wikipedia.org/wiki/Guitar_tuning
theme: "Guitar Standard Tuning"
comment:"EADGBE using 12-TET tuning"
presets: {
    E2=82.41
    A2=110.00
    D3=146.83
    G3=196.00
    B3=246.94
    E4=329.63
}

theme: "Bass Guitar Standard Tuning"
comment: "EADG using 12-TET tuning"
presets: {
    E1=41.204
    A2=55.000
    D3=73.416
    G3=97.999
}

...which need to be extracted into some structure like thi开发者_JS百科s:


@class Preset
{
    NSString* label;
    double freq;
}

@class Theme
{
    NSString* label;
    NSMutableArray* presets;
}

NSMutableArray* themes;

How do I write my file using JSON? ( I would like to create a minimum of typing on the part of the user -- how succinct can I get it? Could someone give me an example for the first theme? )

And how do I parse it into the structures using https://github.com/johnezang/JSONKit?


Here's a valid JSON example based on your thoughts:

[
    {
        "name": "Guitar Standard Tuning",
        "comment": "EADGBE using 12-TET tuning",
        "presets": {
            "E2": "82.41",
            "A2": "110.00",
            "D3": "146.83",
            "G3": "196.00",
            "B3": "246.94",
            "E4": "329.63"
        }
    },
    {
        "name": "Bass Guitar Standard Tuning",
        "comment": "EADG using 12-TET tuning",
        "presets": {
            "E1": "41.204",
            "A1": "55.000",
            "D2": "73.416",
            "G2": "97.999"
        }
    }
]

Read a file and parse using JSONKit:

NSData* jsonData = [NSData dataWithContentsOfFile: path];
JSONDecoder* decoder = [[JSONDecoder alloc]
                             initWithParseOptions:JKParseOptionNone];
NSArray* json = [decoder objectWithData:jsonData];

After that, you'll have to iterate over the json variable using a for loop.


Using the parser in your question and assuming you have Simeon's string in an NSString variable. Here's how to parse it:

#import "JSONKit.h"


id parsedJSON = [myJSONString objectFromJSONString];

That will give you a hierarchy of arrays and dictionaries that you can walk to get your Preset and Theme objects. In the above case, you would get an array with two dictionaries each with a name, comment and presets key. The first two will have NSString values and the third (presets) will have a dictionary as it's value with the note name as keys and the frequencies as values (as NSString objects).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜