使用Swift 4解析JSON数据数组 [英] Parse JSON Data Array with Swift 4

查看:115
本文介绍了使用Swift 4解析JSON数据数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码.仅当JSON数据不是以'['字符开头时,它才起作用.对于以'{'字符开头的JSON数据,它工作正常.这里有一个类似的问题:快速解析JSON数组,但是大多数方法是不推荐使用,我无法使代码正常工作.这是我正在使用的JSON调用:

I am using the following code. It only works if the JSON data does not start with a '[' character. It works fine for JSON data starting with a '{' character. There is a similar question here: Parsing JSON array in swift but most of the methods are deprecated and I was unable to get the code to work. Here is the JSON call I am using:

guard let json = (try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any]        else {
    print("Error: Could not parse JSON!!!")
    return
}

我尝试删除所有选项,并使用allowFragments和mutableLeaves等.据我了解,mutableContainers是默认设置,但我一直在尝试一切可能的方法.任何帮助或建议,将不胜感激.

I tried removing all options and using allowFragments and mutableLeaves among others. From what I understand mutableContainers is a default setting but I have been trying whatever I can. Any help or advice would be much appreciated.

以下是我正在使用的JSON数据的示例:

Here is a sample of the JSON data I am working with:

{"CREATED_BY" =域\用户"; "CREATED_DATE" ="2011-09-30T15:00:13";状态= U; "EMPLOYEE_NUMBER" = 039000292; "UPDATED_BY" =域名\用户";" UPDATED_DATE"=" 2014-08-02T13:22:01;}

{ "CREATED_BY" = "Domain\USER"; "CREATED_DATE" = "2011-09-30T15:00:13"; STATUS = U; "EMPLOYEE_NUMBER" = 039000292; "UPDATED_BY" = "Domain\USER""; "UPDATED_DATE" = "2014-08-02T13:22:01"; }

推荐答案

问题是[]表示json是对象数组,因此您需要将其强制转换为数组.您可以通过将其强制转换为[Any]或将其强制转换为字典数组(实际上就是这样)来实现.

The issue is that the [] signifies that the json is an Array of objects, so you need to cast this to an array. You can do this by either casting it to [Any] or by casting it to an array of dictionaries (which is what it really is).

do {
    let json = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
    let json2 = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] 
} catch {
    print("Error: Couldn't parse JSON. \(error.localizedDescription)")
}

因此在上述代码块中提供了以下json:

So provided the following json to the above block:

let jsonString = """
    [{
        "id": "5",
        "name": "Test",
        "team1": "thingy team",
        "team2": "clicky team",
        "category": "4",
        "end_date": "1415217600",
        "cat_name": "new thingy",
        "team1_bets": 1,
        "team2_bets": 1
    }]
"""

您最终将获得以下输出:

you would end up with an output of the following:

let json = Optional([{
    "cat_name" = "new thingy";
    category = 4;
    "end_date" = 1415217600;
    id = 5;
    name = Test;
    team1 = "thingy team";
    "team1_bets" = 1;
    team2 = "clicky team";
    "team2_bets" = 1;
}])
let json2 = Optional([["team2_bets": 1, "name": Test, "id": 5, "team1_bets": 1, "team2": clicky team, "team1": thingy team, "category": 4, "cat_name": new thingy, "end_date": 1415217600]])

两者之间的主要区别是json的内容是Any对象的数组,然后需要将其强制转换为正在使用的任何数据类型. json2数组是词典的数组,然后您需要强制转换Any对象,但仍具有可用的键.

The main difference between the two is that the contents of json are an array of Any objects, which would then need to be cast to whatever data type you're working with. The json2 array is an array of dictionaries, which you would then need to cast the Any objects but you still have the keys available.

这篇关于使用Swift 4解析JSON数据数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆