【问题标题】:Variable inside JSON stringJSON字符串中的变量
【发布时间】:2020-05-18 17:04:15
【问题描述】:

我正在开发一个制作简历的应用程序,我有一个 JSON 文件,其中包含用户可以选择的职位描述。问题是用户飞行的飞机可能很多,我想在 JSON 字符串中添加一个可以更改的变量。像这样的:

{
"data":[
  {
    "jobDescription": "Worldwide Passenger and freighter flights in all weather conditions, on the modern " + yourAirplane + ". I Have gained experience flying to destinations in all continents while working with different nationalities"
  }
 ]
}

我一直在谷歌搜索,但找不到任何东西。我用以下代码解析字符串:

struct  JobDescriptionData : Decodable{
    var data:[JobDescritpion]?
}

class JobDescritpion:  NSObject, Decodable {

    static let shared = JobDescritpion()

    var jobDescription : String?

    func loadJobDescriptions(completion: ([JobDescritpion]) -> ()){
        let path = Bundle.main.path(forResource: "jobDescription", ofType: "json")!
                do {
                    let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
                    data.printJSON()
                    let decoder = JSONDecoder()
                    guard let eventResult = try? decoder.decode(JobDescriptionData.self, from: data) else { return }

                    var array = [JobDescritpion]()
                    array = eventResult.data!
                    completion(array)

                    } catch {
                }
    }
}

printJSON()(这是我对 Data 的扩展,用于打印 json 数组)可以工作,它会返回数组,但当然,由于jobDescription 不是字符串,所以守卫失败了。

关于如何添加变量然后稍后在应用程序中设置它的任何建议?

【问题讨论】:

  • 这个变量从何而来?也许您正在寻找类似本地化字符串中的占位符之类的东西。
  • 用户添加了他的飞行时间,这样我就可以知道他驾驶的是什么飞机。我有一个与这架飞机有关的数组,因此当用户为该特定工作/飞机选择工作描述时,就会设置该变量。我不确定是否清楚。

标签: ios json swift


【解决方案1】:

为您的 JSON 使用字符串格式

例子

let stringTemplate = "Worldwide Passenger and freighter flights in all weather conditions, on the modern %@. I Have gained experience flying to destinations in all continents while working with different nationalities"

let formattedString = String(format: stringTemplate , "some value")
print(formattedString)

【讨论】:

    【解决方案2】:

    将 JSON 保存为字符串:

    {
        "data": [{
            "jobDescription": "Worldwide Passenger and freighter flights in all weather conditions, on the modern <yourAirplane>. I Have gained experience flying to destinations in all continents while working with different nationalities"
        }]
    }
    

    解码后:

    "description".replacingOccurrences(of: "<yourAirplane>", with: yourAirplane)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      相关资源
      最近更新 更多