简体   繁体   English

JSON 数据无法读取

[英]JSON data couldn’t be read

I am trying to replicate following GET request in my project:我正在尝试在我的项目中复制以下 GET 请求:

curl -XGET 'https://api2.branch.io/v1/url?url=https://example.app.link/WgiqvsepqF&branch_key=key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt'

Here is my final code:这是我的最终代码:

if let url = URL(string: "https://example.app.link/WgiqvsepqF&branch_key=key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt"){
            let urlRequest = URLRequest(url: url)
            URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
                if error == nil{
                    do{
                        if let dataReceived = data, let jsonData = try JSONSerialization.jsonObject(with: dataReceived, options: .mutableLeaves) as? [String : Any]{
                            print(jsonData)
                        }
                    } catch let error{
                        print(error.localizedDescription)
                    }
                }
                }.resume()
        }

I am getting following error:我收到以下错误:

The data couldn't be read because it isn't in the correct format.无法读取数据,因为它的格式不正确。

I tried other Stackoverflow and Reddit solution but nothing seems to be working.我尝试了其他 Stackoverflow 和 Reddit 解决方案,但似乎没有任何效果。

API call is returning data keys in wrong format. API 调用以错误的格式返回数据键。 You are receiving the keys starting from '$' or '~' eg '$og_title', '~stage'.您正在接收从“$”或“~”开始的密钥,例如“$og_title”、“~stage”。 That's why it's showing you an error.这就是它向您显示错误的原因。

  • You can use Codable to parse the API.您可以使用 Codable 来解析 API。 For that first, you need to make a Model struct for your API Call.首先,您需要为您的 API 调用创建一个 Model 结构。
  • Change the variable names according to Swift Syntax.根据 Swift 语法更改变量名称。 I've replaced '$' with 'l' and '~' with 'i'.我已经用 'l' 和 '~' 替换了 '$' 和 'i'。 You can customize the code according to your needs.您可以根据需要自定义代码。

This is your API Call这是您的 API 电话

let url = URL(string: "https://api2.branch.io/v1/url?url=https://example.app.link/WgiqvsepqF&branch_key=key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt")
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "GET"

let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
    guard ((data) != nil), let _: URLResponse = response, error == nil else {
        print("error")
        return
    }
    if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
        print(dataString)
        do {
            //here dataResponse received from a network request
            let decoder = JSONDecoder()
            let model = try decoder.decode(ResponseData.self, from: data!) //Decode JSON Response Data
            // Access your json data from Swift Structs e.g. model.type
            print(model.data?.iurl)
        } catch let parsingError {
            print("Error", parsingError)
        }
    }
})
task.resume()

This is your Model Struct这是你的 Model 结构

struct ResponseData : Codable {

    let data : MyData?
    let type : Int?
    let tags : [String]?
    let campaign : String?
    let feature : String?
    let channel : String?
    let stage : String?

    enum CodingKeys: String, CodingKey {

        case data = "data"
        case type = "type"
        case tags = "tags"
        case campaign = "campaign"
        case feature = "feature"
        case channel = "channel"
        case stage = "stage"
    }            
}

struct MyData : Codable {
    let custom_array : [Int]?
    let log_title : String?
    let custom_boolean : Bool?
    let custom_integer : Int?
    let icreation_source : Int?
    let log_description : String?
    let log_image_url : String?
    let istage : String?
    let custom_string : String?
    let ifeature : String?
    let url : String?
    let custom_object : Custom_object?
    let iurl : String?
    let ldesktop_url : String?
    let itags : [String]?
    let lcanonical_identifier : String?
    let lone_time_use : Bool?
    let iid : String?
    let icampaign : String?
    let ichannel : String?

    enum CodingKeys: String, CodingKey {

        case custom_array = "custom_array"
        case log_title = "$og_title"
        case custom_boolean = "custom_boolean"
        case custom_integer = "custom_integer"
        case icreation_source = "~creation_source"
        case log_description = "$og_description"
        case log_image_url = "$og_image_url"
        case istage = "~stage"
        case custom_string = "custom_string"
        case ifeature = "~feature"
        case url = "url"
        case custom_object = "custom_object"
        case iurl = "+url"
        case ldesktop_url = "$desktop_url"
        case itags = "~tags"
        case lcanonical_identifier = "$canonical_identifier"
        case lone_time_use = "$one_time_use"
        case iid = "~id"
        case icampaign = "~campaign"
        case ichannel = "~channel"
    }

}

struct Custom_object : Codable {
    let random : String?

    enum CodingKeys: String, CodingKey {

        case random = "random"
    }

}

The decoding code is correct.解码代码是正确的。

The link is wrong, it should be https://api2.branch.io/v1/url?url=https://example.app.link/WgiqvsepqF&branch_key=key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt and not https://example.app.link/WgiqvsepqF&branch_key=key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt The link is wrong, it should be https://api2.branch.io/v1/url?url=https://example.app.link/WgiqvsepqF&branch_key=key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt and not https://example.app.link/WgiqvsepqF&branch_key=key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt

Only decoding:仅解码:

import UIKit

var json = """
{

    "data": {
        "custom_array": [
            1,
            2,
            3,
            4,
            5,
            6
        ],
        "$og_title": "Title from Deep Link",
        "custom_boolean": true,
        "custom_integer": 1243,
        "~creation_source": 0,
        "$og_description": "Description from Deep Link",
        "$og_image_url": "http://www.lorempixel.com/400/400/",
        "~stage": "new user",
        "custom_string": "everything",
        "~feature": "onboarding",
        "url": "https://example.app.link/WgiqvsepqF",
        "custom_object": {
            "random": "dictionary"
        },
        "+url": "https://example.app.link/WgiqvsepqF",
        "$desktop_url": "http://www.example.com",
        "~tags": [
            "one",
            "two",
            "three"
        ],
        "$canonical_identifier": "content/123",
        "$one_time_use": false,
        "~id": "423196192848102356",
        "~campaign": "new product",
        "~channel": "facebook"
    },
    "type": 0,
    "tags": [
        "one",
        "two",
        "three"
    ],
    "campaign": "new product",
    "feature": "onboarding",
    "channel": "facebook",
    "stage": "new user"

}
"""

let data = json.data(using: .utf8)!
do {
  if let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String : Any] {
    print(jsonData)
}
} catch let error {
  print(error)
}

暂无
暂无

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

相关问题 Swift 从 API 解析 json - 无法读取数据,因为它的格式不正确 - Swift parse json from API - The data couldn’t be read because it isn’t in the correct format swift 解析 json - 无法读取数据,因为它的格式不正确 - swift parse json - The data couldn’t be read because it isn’t in the correct format SWIFT - JSON 错误:无法读取数据,因为它的格式不正确 - SWIFT - JSON error: The data couldn’t be read because it isn’t in the correct format 无法解码 JSON:无法读取数据,因为它的格式不正确 - Could not decode JSON: The data couldn’t be read because it isn’t in the correct format JSON API 错误 - 由于数据丢失,无法读取数据。 - JSON API Error- The data couldn’t be read because it is missing.- in iOS, swift 在 Swift 中解码 JSON 时出现“数据无法读取,因为它丢失”错误 - “The data couldn’t be read because it is missing” error when decoding JSON in Swift 无法在IOS 5上使用Json解析数据 - Couldn't parse data using Json on IOS 5 如何存储 Json 注册响应 API? 并出现“无法读取数据,因为它的格式不正确”的错误。 - How to Store Json Response Of Registration API ? and Getting error of "The data couldn’t be read because it isn’t in the correct format." 由于错误,JSON 无法序列化:无法读取数据,因为它的格式不正确。[Swift 4.2] - JSON could not be serialized because of error: The data couldn’t be read because it isn’t in the correct format.[Swift 4.2] 无法读取数据,因为格式不正确 - The data couldn’t be read because it isn’t in the correct format
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM