-2

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?

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
Tomas
  • 135
  • 1
  • 6
  • The json in the duplicate question has a string array inside a dictionary instead of at the top level but apart from that the solution is the same – Joakim Danielson Jun 27 '22 at 06:31

2 Answers2

3

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)
 }
Paulw11
  • 108,386
  • 14
  • 159
  • 186
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • When I use a [String] I get the following error: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0}))) – Tomas Jun 27 '22 at 03:52
0

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]
Jack Will
  • 160
  • 2
  • 7