如何从{}内的JSON解析数据?

时间:2019-05-17 22:25:14

标签: ios json swift string

嘿,我正在尝试从下面的API中解析一些数据,但是正如您在链接中所看到的那样,某些数据在{0},{1}下...这是一种形式,我认为为什么我无法解析通过使用此行代码来获取数据?

https://financialmodelingprep.com/api/v2/financials/income-statement/AAPL?datatype=json

func updateStockData(json : JSON)
{

    if let revenue = json["financials"]["5"]["Revenue"].double
    {
        print(revenue)
        stockPriceLabel.text = "$" + String(revenue)
    }
    else
    {
        print("unavaiable")
    }
}

3 个答案:

答案 0 :(得分:0)

键“ finiancials”的值是一个数组,因此您必须使用整数对其进行索引。另外,JSON中的收益是一个字符串,因此您必须照此读取并手动将其转换为双精度值:

if let revenueString = json["financials"][5]["Revenue"].string, let revenue = Double(revenueString) {
    ...
}

答案 1 :(得分:0)

您应该对数据进行结构化并使其符合要求。您可以使用quicktype网站将json字符串转换为Swift结构:

struct Root: Codable {
    let symbol: String
    let financials: [Financial]
}

struct Financial: Codable {
    let date: String
    let revenue: String
    let costOfRevenue: String
    let grossProfit: String
    let researchAndDevelopment: String
    let salesGeneralAndAdministrative: String
    let totalOperatingExpenses: String
    let operatingIncome: String
    let interestExpense: String
    let otherIncomeExpense: String
    let incomeBeforeTaxes: String
    let provisionForIncomeTaxes: String
    let netIncomeFromContinuingOperations: String
    let netIncome: String
    let netIncomeAvailableToCommonShareholders: String
    let earningsPerShareBasic: String
    let earningsPerShareDiluted: String
    let weightedAverageSharesOutstandingBasic: String
    let weightedAverageSharesOutstandingDiluted: String
    let ebitda: String

    enum CodingKeys: String, CodingKey {
        case date,
        revenue = "Revenue",
        costOfRevenue = "Cost of revenue",
        grossProfit = "Gross profit",
        researchAndDevelopment = "Research and development",
        salesGeneralAndAdministrative = "Sales, General and administrative",
        totalOperatingExpenses = "Total operating expenses",
        operatingIncome = "Operating income",
        interestExpense = "Interest Expense",
        otherIncomeExpense = "Other income (expense)",
        incomeBeforeTaxes = "Income before taxes",
        provisionForIncomeTaxes = "Provision for income taxes",
        netIncomeFromContinuingOperations = "Net income from continuing operations",
        netIncome = "Net income",
        netIncomeAvailableToCommonShareholders = "Net income available to common shareholders",
        earningsPerShareBasic = "Earnings per share basic",
        earningsPerShareDiluted = "Earnings per share diluted",
        weightedAverageSharesOutstandingBasic = "Weighted averageShares outstanding basic",
        weightedAverageSharesOutstandingDiluted = "Weighted averageShares outstanding diluted",
        ebitda = "EBITDA"
    }
}

游乐场测试

let json = """
{ "symbol": "AAPL", "financials": [ { "date": "2014-09", "Revenue": "182795", "Cost of revenue": "112258", "Gross profit": "70537", "Research and development": "6041", "Sales, General and administrative": "11993", "Total operating expenses": "18034", "Operating income": "52503", "Interest Expense": "384", "Other income (expense)": "1364", "Income before taxes": "53483", "Provision for income taxes": "13973", "Net income from continuing operations": "39510", "Net income": "39510", "Net income available to common shareholders": "39510", "Earnings per share basic": "6.49", "Earnings per share diluted": "6.45", "Weighted averageShares outstanding basic": "6086", "Weighted averageShares outstanding diluted": "6123", "EBITDA": "61813" }, { "date": "2015-09", "Revenue": "233715", "Cost of revenue": "140089", "Gross profit": "93626", "Research and development": "8067", "Sales, General and administrative": "14329", "Total operating expenses": "22396", "Operating income": "71230", "Interest Expense": "733", "Other income (expense)": "2018", "Income before taxes": "72515", "Provision for income taxes": "19121", "Net income from continuing operations": "53394", "Net income": "53394", "Net income available to common shareholders": "53394", "Earnings per share basic": "9.28", "Earnings per share diluted": "9.22", "Weighted averageShares outstanding basic": "5753", "Weighted averageShares outstanding diluted": "5793", "EBITDA": "84505" }, { "date": "2016-09", "Revenue": "215639", "Cost of revenue": "131376", "Gross profit": "84263", "Research and development": "10045", "Sales, General and administrative": "14194", "Total operating expenses": "24239", "Operating income": "60024", "Interest Expense": "1456", "Other income (expense)": "2804", "Income before taxes": "61372", "Provision for income taxes": "15685", "Net income from continuing operations": "45687", "Net income": "45687", "Net income available to common shareholders": "45687", "Earnings per share basic": "8.35", "Earnings per share diluted": "8.31", "Weighted averageShares outstanding basic": "5471", "Weighted averageShares outstanding diluted": "5500", "EBITDA": "73333" }, { "date": "2017-09", "Revenue": "229234", "Cost of revenue": "141048", "Gross profit": "88186", "Research and development": "11581", "Sales, General and administrative": "15261", "Total operating expenses": "26842", "Operating income": "61344", "Interest Expense": "2323", "Other income (expense)": "5068", "Income before taxes": "64089", "Provision for income taxes": "15738", "Net income from continuing operations": "48351", "Net income": "48351", "Net income available to common shareholders": "48351", "Earnings per share basic": "9.27", "Earnings per share diluted": "9.21", "Weighted averageShares outstanding basic": "5217", "Weighted averageShares outstanding diluted": "5252", "EBITDA": "76569" }, { "date": "2018-09", "Revenue": "265595", "Cost of revenue": "163756", "Gross profit": "101839", "Research and development": "14236", "Sales, General and administrative": "16705", "Total operating expenses": "30941", "Operating income": "70898", "Interest Expense": "3240", "Other income (expense)": "5245", "Income before taxes": "72903", "Provision for income taxes": "13372", "Net income from continuing operations": "59531", "Net income": "59531", "Net income available to common shareholders": "59531", "Earnings per share basic": "12.01", "Earnings per share diluted": "11.91", "Weighted averageShares outstanding basic": "4955", "Weighted averageShares outstanding diluted": "5000", "EBITDA": "87046" }, { "date": "TTM", "Revenue": "261612", "Cost of revenue": "161654", "Gross profit": "99958", "Research and development": "14731", "Sales, General and administrative": "17257", "Total operating expenses": "31988", "Operating income": "67970", "Interest Expense": "3396", "Other income (expense)": "5205", "Income before taxes": "69779", "Provision for income taxes": "10348", "Net income from continuing operations": "59431", "Net income": "59431", "Net income available to common shareholders": "59431", "Earnings per share basic": "12.31", "Earnings per share diluted": "12.20", "Weighted averageShares outstanding basic": "4861", "Weighted averageShares outstanding diluted": "4904", "EBITDA": "84728" } ] }
"""

do {
    let root = try JSONDecoder().decode(Root.self, from: Data(json.utf8))
    let revenue = root.financials[5].revenue 
    print(revenue)   //  "261612"
} catch {
    print(error)
}

答案 2 :(得分:0)

我使用SwiftBooster库(由我自己编写)进行了测试,并且运行良好。无需创建用于对JSON建模或将String值转换为Double的结构或类。

import SwiftBooster

func updateStockData(json : JSON)
{

    if let revenue: Double = getValue(input: response.responseJsonObject, subscripts: "financials", 5, "Revenue")
    {
        print(revenue)
        stockPriceLabel.text = "$" + String(revenue)
    }
    else
    {
        print("unavaiable")
    }
}

请注意,第二个密钥应使用5,而不是"5"