swift json parse返回可选

时间:2018-05-08 20:07:28

标签: json swift

我试图在swift中解析json响应并且很难做到这一点。当我引用json字符串的顶级,并打印该值时,我得到一个Optional(< __ NSSingleObjectArrayI),然后是json的值

打印到控制台时我得到:

Optional(<__NSSingleObjectArrayI 0x1c0014180>(
{
ack =     (
    Success
);
paginationOutput =     (
            {

然后剩下的json

我不知道可选项正在做什么或为什么它在那里,但它似乎阻碍了我试图做的其余解析,因为当我尝试进入嵌套值的下一级时它总是返回零。

进行解析的代码如下

URLSession.shared.dataTask(with: endpoint) { (data, response, error) in
        do {
            guard let data = data else {
                return
            }
            guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary else {
                return
            }

            //print(json)
            print(json.object(forKey: "findCompletedItemsResponse"))
            let dictionary1 = json.object(forKey: "findCompletedItemsResponse")

            print(dictionary1)
        } catch let error {
            print(error)
        }
        }.resume()

2 个答案:

答案 0 :(得分:0)

使用body{ background-image: url(image.jpg); background-size: cover; border-image-repeat: no-repeat; } 打开以下值:

if-let

答案 1 :(得分:0)

swift中不需要.allowFragments

如果您的json["findCompletedItemsResponse"]是字典类型,那么它可以解析如下:

URLSession.shared.dataTask(with: endpoint) { (data, response, error) in
    do {
        guard let data = data, let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
            return
        }

        if let dictionary1 = json["findCompletedItemsResponse"] as? [String: Any] {
             print(dictionary1)
        } else {
            print(json["findCompletedItemsResponse"])
        }
    } catch let error {
        print(error)
    }
    }.resume()