代码之家  ›  专栏  ›  技术社区  ›  LondonGuy

我无法在Swift 5[重复]中解码JSON

  •  -1
  • LondonGuy  · 技术社区  · 6 年前

    有人能告诉我我做错了什么吗?我已经看过这里所有的问题了 How to decode a nested JSON struct with Swift Decodable protocol? 我找到了一个似乎正是我需要的 Swift 4 Codable decoding json .

    {
    "success": true,
    "message": "got the locations!",
    "data": {
        "LocationList": [
            {
                "LocID": 1,
                "LocName": "Downtown"
            },
            {
                "LocID": 2,
                "LocName": "Uptown"
            },
            {
                "LocID": 3,
                "LocName": "Midtown"
            }
         ]
      }
    }
    
    struct Location: Codable {
        var data: [LocationList]
    }
    
    struct LocationList: Codable {
        var LocID: Int!
        var LocName: String!
    }
    
    class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let url = URL(string: "/getlocationlist")
    
        let task = URLSession.shared.dataTask(with: url!) { data, response, error in
            guard error == nil else {
                print(error!)
                return
            }
            guard let data = data else {
                print("Data is empty")
                return
            }
    
            do {
                let locList = try JSONDecoder().decode(Location.self, from: data)
                print(locList)
            } catch let error {
                print(error)
            }
        }
    
        task.resume()
    }
    

    我得到的错误是:

    类型不匹配(Swift.Array,Swift.DecodingError.Context(codingPath: [],debugDescription:“本应解码数组,但发现一个 改用字典。“,参考错误:无”)

    0 回复  |  直到 8 年前
        1
  •  8
  •   OOPer    8 年前

    检查JSON文本的大致结构:

    {
        "success": true,
        "message": "got the locations!",
        "data": {
          ...
        }
    }
    

    价值 "data" 是一个JSON对象 {...} ,它不是数组。 以及物体的结构:

    {
        "LocationList": [
          ...
        ]
    }
    

    该对象只有一个条目 "LocationList": [...] 它的值是一个数组 [...] .

    您可能还需要一个结构:

    struct Location: Codable {
        var data: LocationData
    }
    
    struct LocationData: Codable {
        var LocationList: [LocationItem]
    }
    
    struct LocationItem: Codable {
        var LocID: Int!
        var LocName: String!
    }
    

    为了测试。。。

    var jsonText = """
    {
        "success": true,
        "message": "got the locations!",
        "data": {
            "LocationList": [
                {
                    "LocID": 1,
                    "LocName": "Downtown"
                },
                {
                    "LocID": 2,
                    "LocName": "Uptown"
                },
                {
                    "LocID": 3,
                    "LocName": "Midtown"
                }
            ]
        }
    }
    """
    
    let data = jsonText.data(using: .utf8)!
    do {
        let locList = try JSONDecoder().decode(Location.self, from: data)
        print(locList)
    } catch let error {
        print(error)
    }
    
        2
  •  0
  •   Al Walid Ashik    6 年前

    在互联网上搜索了很多东西后,我发现这是从任何对象打印格式良好的json的最佳方式。

    let jsonString = object.toJSONString(prettyPrint: true)
    print(jsonString as AnyObject)
    
        3
  •  0
  •   Vassily    5 年前

    关于JSONECODER的苹果文档->

    struct GroceryProduct: Codable {
        var name: String
        var points: Int
        var description: String?
    }
    
    let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.")
    
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    
    let data = try encoder.encode(pear)
    print(String(data: data, encoding: .utf8)!)
    
    /* Prints:
     {
       "name" : "Pear",
       "points" : 250,
       "description" : "A ripe pear."
     }
    */