user3069232
user3069232

Reputation: 8995

Using SwiftyJSON package

Trying to use SwiftyJSON library, but struggling for a day or so now.

I got this JSON.

“blah”:[{“xdeltaY":0,"xdeltaX":0,"blah1":435,"blah2":"\/Numbers\/Numbers.001.png","height":693.2142857142857,"width":1200,"blah3":240}]

I read it in from a file and assign it like this?

let quickfix  = String(data: response.1, encoding: String.Encoding.utf8)
let json2F = JSON(quickfix!)

It seems to work. I can print this.

json2F.debugDescription

But I can do next to nothing beyond that. It hasn't parsed seems, I think it is just a string.

I am unable to figure out how to access the data within it. I also tried this...

if let dataFromString = quickfix?.data(using: .utf8, allowLossyConversion: false) {
                    let json2E = JSON(data: dataFromString)
                    print("json2E debugDescription \(json2F.debugDescription)")
                }

But it returns null!! How to use this library?

Upvotes: 0

Views: 57

Answers (1)

kiecodes
kiecodes

Reputation: 1659

You code looks good to me. It seems that your JSON is not valid.

Try to put an encapsulating object {} around it. Like this:

{"blah": [{"xdeltaY":0, "xdeltaX":0, "blah1":435, "blah2":"\/Numbers\/Numbers.001.png", "height":693.2142857142857, "width":1200, "blah3":240}]}

And additionally make sure you are using the right "not .

String+JSON

I also like to share a extension I use for getting my JSON from a string, which also gives you error messages in the console logs to prevent invalid JSON to mess up your program.

import Foundation
import SwiftyJSON

public extension String {
    public func toJSON() -> JSON? {
        if let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false) {
            var jsonError: NSError?
            let json = JSON(data: data, error: &jsonError)
            if jsonError == nil {
                return json
            } else {
                print(jsonError!.description)
            }
        }
        return nil
    }

    public func toJSONValue() -> JSON {
        return self.toJSON() ?? JSON.null
    }
}

Upvotes: 1

Related Questions