JSON字符串中的变量

我正在开发制作简历的应用,并且我有一个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() (which is my extension to Data to print the json array) works and it returns the array but of course, the guard let fails because jobDescription is not a string.

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

评论
  • SOS
    SOS 回复

    将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)
    
  • duang
    duang 回复

    对您的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)