简体   繁体   English

使用swiftyJSON在Swift 2.0中解析JSON时获取空值

[英]Getting a null value when parsing JSON in Swift 2.0 with swiftyJSON

I'm getting a null value when I try to parse json from a url. 当我尝试从URL解析json时,我得到的是空值。 What am I missing, or what should I be implementing to simply load a json value and put inside of a UICollectionView ? 我在想什么,或者我应该怎么来实现简单地加载一个JSON值,并把里面的UICollectionView

This is json I get from the web service. 这是我从Web服务获得的json。 I have validated it with a validation tool and it is correct: 我已经使用验证工具对其进行了验证,它是正确的:

{
    "status": 1,
    "count": 72,
    "data": [
        {
            "id": 818,
            "name": "1. product",
            "price": "155.00"
        },
        {
            "id": 812,
            "name": "2. product",
            "price": "62.00"
        },
       {
            "id": 26,
            "name": "3. product",
            "price": "213.00"
        },
       {
            "id": 657,
            "name": "4. product",
            "price": "21.00"
        },
       {
            "id": 347,
            "name": "5. product",
            "price": "57.00"
        }

I need to get the name and price values from the above json. 我需要从上面的json获取名称和价格值。

This is the swiftyJSON code block called in viewDidLoad . 这是在viewDidLoad调用的swiftyJSON代码块。 I suspect the problem is here, but I'm not sure. 我怀疑问题出在这里,但我不确定。

let json = JSON(data: products)
if let productName = json["data"][0]["name"].string {
    print("Product: \(productName)")
}

You could simply avoid null fields in JSON by overriding init function in your model class. 您可以通过覆盖模型类中的init函数来简单地避免JSON中的空字段。 Depend of your mapping data of course. 当然取决于您的映射数据。 If you will get JSON null object, this constructor will simply replace null to default value 如果您将获得JSON空对象,则此构造方法将简单地将null替换为默认值

For example: 例如:

override init() {
   mapField1 = "" // string value
   mapField2 = 0 // number value
}

About ur code. 关于我们的代码。 Where did you take 0 key in your JSON? 您在JSON的哪儿输入了0键? It's only json["data.name"] or json["data.price"] 只是json["data.name"]json["data.price"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM