简体   繁体   English

用 Swift Xcode 创建 JSON object

[英]Create JSON object with Swift Xcode

I have a JSON object below that uses everything from Strings, Bools and Int's.我在下面有一个 JSON object,它使用了 Strings、Bools 和 Int 的所有内容。 I'm currently having a difficult time recreating the person_details section of the object and I think because it's in brackets and has multiple values, like [String: Bool] , [String: String] & [String: Int] ?我目前很难重新创建 object 的person_details部分,我认为是因为它在括号中并且具有多个值,例如[String: Bool][String: String][String: Int]

I posted towards the bottom what populates on the console, but any help structuring there person_details section in the would be great.我在底部发布了控制台上填充的内容,但是任何帮助构建那里的 person_details 部分都会很棒。 You'll see below, in my let order, I'm structuring the data.您将在下面看到,在我的订单中,我正在构建数据。

let testJson = """
{
"household": {
    "region": "PA",
    "household_size": 1,
    "receiving_benefits": [
    ],
    "energy_crisis": false,
    "utility_providers": [
        "peco"
    ],
    "residence_type": "other",
    "property_tax_past_due": false,
    "home_needs_repairs": false,
    "filed_previous_year_tax_return": false,
    "heating_system_needs_repairs": false,
    "at_risk_of_homelessness": false,
    "received_maximum_benefit": {
        "cip": false
    },
    "person_details": [
        {
            "age": 18,
            "marital_status": "single",
            "minimum_employment_over_extended_period": false,
            "work_status": "recent_loss",
            "pregnant": false,
            "attending_school": false,
            "disabled": false
        }
    ],
    "incomes": [
        {
            "gross_monthly_amount": 700,
            "countable_group": "household",
            "year": "current"
        },
        {
            "gross_monthly_amount": 700,
            "countable_group": "household",
            "year": "previous"
        }
    ],
    "assets": [
        {
            "amount": 1000,
            "countable_group": "household"
        }
    ]
}
}
"""

struct Eligibility: Encodable {
    let residence: String
    let hhmembers: Int
    let receivingBen: [String]
    let unhoused: Bool
    let utilityType: [String]
    let residenceType: String
    let propertyTax: Bool
    let homeRepairs: Bool
    let fileLastTax: Bool
    let heatRepairs: Bool
    let receivingMax: [String: Bool]

    enum CodingKeys: String, CodingKey {
        case residence = "region"
        case hhmembers = "household_size"
        case receivingBen = "receiving_benefits"
        case unhoused = "at_risk_of_homelessness"
        case utilityType = "utility_providers"
        case residenceType = "residence_type"
        case propertyTax = "property_tax_past_due"
        case homeRepairs = "home_needs_repairs"
        case fileLastTax = "filed_previous_year_tax_return"
        case heatRepairs = "heating_system_needs_repairs"
        case receivingMax = "received_maximum_benefit"
    }
}

struct PersonDetails: Encodable {
            let age: Int
           //  let marital_status: String
            // let minimum_employment_over_extended_period: Bool
            // let work_status: String
           //  let pregnant: Bool
            // let attending_school: Bool
           //  let disabled: Bool
    
    enum CodingKeys: String, CodingKey {
        case age = "age"
      //  case marital_status = "marital_status"
      //  case minimum_employment_over_extended_period = "minimum_employment_over_extended_period"
      //  case work_status = "work_status"
      //  case pregnant = "pregnant"
      //  case attending_school = "attending_school"
      //  case disabled = "disabled"
    }
}

I believe What I'm missing is inside the let order = , see below:我相信我所缺少的是在let order =中,见下文:

struct Order: Encodable {
    let household: Eligibility
    let person_details: PersonDetails
}
 
let order = Order(household: Eligibility(residence: "PA", hhmembers: 1, receivingBen: [], unhoused: false, utilityType: ["Peco"], residenceType: "other", propertyTax: false, homeRepairs: false, fileLastTax: false, heatRepairs: false, receivingMax: ["cip": false]), person_details: PersonDetails(age: 19))



let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

let orderJsonData = try! encoder.encode(order)

print(String(data: orderJsonData, encoding: .utf8)!)

Inside the Console shows that person_details in outside of 'household' but I would need the person_details inside of the household object as the above full JSON object shows at the top of the question (note square brackets too).控制台内部显示“家庭”之外的 person_details,但我需要家庭内部的 person_details object,因为上面的完整 JSON object 显示在问题的顶部(也请注意方括号)。 Console below:下面的控制台:

{
  "household" : {
    "region" : "PA",
    "residence_type" : "other",
    "at_risk_of_homelessness" : false,
    "property_tax_past_due" : false,
    "utility_providers" : [
      "Peco"
    ],
    "home_needs_repairs" : false,
    "filed_previous_year_tax_return" : false,
    "household_size" : 1,
    "receiving_benefits" : [

    ],
    "heating_system_needs_repairs" : false,
    "received_maximum_benefit" : {
      "cip" : false
    }
  },
  "person_details" : {
    "age" : 19
  }
}

You've got the structure of your data hierarchy wrong converting from JSON to swift.您的数据层次结构错误地从 JSON 转换为 swift。

It should be...它应该是...

struct Order: Codable {
   let household: Household
}

struct Household: Codable {
   let personDetails: [Person]
}

struct Person: Codable {
   let age: Int
   let maritalStatus: String
   let minimumEmploymentOverExtendedPeriod: Bool
   let workStatus: String
   let pregnant: Bool
   let attendingSchool: Bool
   let disabled: Bool
}

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let order = try! decoder.decode(Order.self, from: Data(testJson.utf8))

returns回报

Person(age: 18, maritalStatus: "single", minimumEmploymentOverExtendedPeriod: false, workStatus: "recent_loss", pregnant: false, attendingSchool: false, disabled: false)]人(年龄:18,maritalStatus:“单身”,minimumEmploymentOverExtendedPeriod:false,workStatus:“recent_loss”,怀孕:false,attendingSchool:false,disabled:false)]

Also worth pointing out is the use of the .keyDecodingStrategy to ease the converting from snake case.还值得指出的是使用.keyDecodingStrategy来简化从 snake case 的转换。 This saves defining the CodingKeys .这节省了定义CodingKeys Obviously this will only work where you're happy to keep the naming the same.显然,这只适用于您愿意保持命名相同的情况。

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

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