0

I am trying to separate out before, range and after from the JSON below and store them in different arrays/dictionaries. However I am able to parse only range. Can anyone please help with an example?

{
    "before": [
        {
            "segment": 1,
            "end": 0,
            "size": 0
        },
        {
            "segment": 2,
            "end": 0.01,
            "size": 0.1
        }
    ],
    "range": [
        100,
        101,
        102,
        103,
        104,
        105,
        106,
        107,
        108,
        109,
        110
    ],
    "after": [
        {
            "segment": 1,
            "end": 0,
            "size": 0
        },
        {
            "segment": 2,
            "end": 0.5,
            "size": 0.1
        },
        {
            "segment": 3,
            "end": 0.8,
            "size": 0.3
        },
        {
            "segment": 4,
            "end": 1,
            "size": 0.5
        }
    ]
}
0

1 Answer 1

2

All you have to do is to cast the content to the right type.

You JSON object is a dictionary; "before" is an array of dictionaries, "after" is similar, and "range" is an array of Ints.

Knowing this, it's easy to decode:

if let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []) {
    if let dict = json as? [String:AnyObject] {
        if let before = dict["before"] as? [[String:AnyObject]] {
            print(before)
        }
        if let after = dict["after"] as? [[String:AnyObject]] {
            print(after)
        }
        if let range = dict["range"] as? [Int] {
            print(range)
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.