1

here is How i parse json:

let myObject = MyObject()
let string1 = if jsonObject["string1"] as? String{
    myObject.string1 = string1
}else{
  throw InValidJson
}

let string2 = if jsonObject["string2"] as? String{
    myObject.string2 = string2
}else{
  throw InValidJson
}

let string3 = if jsonObject["string3"] as? String{
    myObject.string3 = string3
}else{
  throw InValidJson
}

but that too much code, as i am using if every where, is it possible to do something like the following:

do{
   myObject.string1 = if jsonObject["string1"] as! String
   myObject.string2 = if jsonObject["string2"] as! String
   myObject.string3 = if jsonObject["string3"] as! String

}catch(){
   error.description
}

so i don't need to check every key, as my json is too large.

Thanks

1 Answer 1

1

You can do this:

guard let string1 = jsonObject["string1"] as? String,
  string2 = jsonObject["string2"] as? String,
  string3 = jsonObject["string3"] as? String else {
  //handle error
  return
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your answer, is it possible to check which keys cause error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.