skip to Main Content

I am trying to access each title in a returned json. This is the JSON

[
    "Hyouka",
    "Youjo Senki",
    "Bungou Stray Dogs 2nd Season",
    "Fullmetal Alchemist: Brotherhood",
    "Tokyo Ghoul √A",
    "Mahouka Koukou no Rettousei",
    "Boku wa Tomodachi ga Sukunai NEXT",
    "Joker Game",
    "Avatar: The Last Airbender",
    "Charlotte"
]

It’s just a bunch of values and no key for me to construct my model object. This is how I would plan to do it

struct AllNames {
    
    let name: String   
}

But there’s no key name for me to access. How would you go about accessing this data to print each name to the console in Swift?

2

Answers


  1. Your json is an array of strings , so no model is here and you only need

    do {
        let arr = try JSONDecoder().decode([String].self, from: jsonData)
        print(arr)
     }
     catch {
        print(error)
     }
    
    Login or Signup to reply.
  2. Convert JSON string to array:

        func getArrayFromJSONString(jsonStr: String) -> Array<Any> {
            
            let jsonData: Data = jsonStr.data(using: .utf8)!
         
            let arr = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
            
            if arr != nil {
                return arr as! Array<Any>
            }
            
            return []
        }
    

    Test case:

        let jsonStr = """
        [
            "Hyouka",
            "Youjo Senki",
            "Bungou Stray Dogs 2nd Season",
            "Fullmetal Alchemist: Brotherhood",
            "Tokyo Ghoul √A",
            "Mahouka Koukou no Rettousei",
            "Boku wa Tomodachi ga Sukunai NEXT",
            "Joker Game",
            "Avatar: The Last Airbender",
            "Charlotte"
        ]
        """
        
        let arr = getArrayFromJSONString(jsonStr: jsonStr)
        
        print(arr)
    

    Print log:

    [Hyouka, Youjo Senki, Bungou Stray Dogs 2nd Season, Fullmetal Alchemist: Brotherhood, Tokyo Ghoul √A, Mahouka Koukou no Rettousei, Boku wa Tomodachi ga Sukunai NEXT, Joker Game, Avatar: The Last Airbender, Charlotte]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search