Understanding Perth of JSON Data from API

Asked 1 years ago, Updated 1 years ago, 49 views

I got the book information using Google API.

{"totalItems":int,
 "items":[{"kind":"books#volume",
            "volumeInfo": {"title": "hoge",
                            "authors": ["name",
                            "publishedDate": "2014-06-20"}]}

I don't know how to extract the contents of authors as a string when parsing json like this

.
let authors=volumeInfo?["authors"] as!String
print (authors)

If you write

Could not cast value of type
'NSSingleObjectArrayI' (0x3b5244d0) to 'NSString' (0x3b52d0ac)

It appears as follows:
How can I describe the contents of the authorities so that they can be taken out and handled?
I would appreciate it if you could let me know.

swift json

2022-09-29 21:48

1 Answers

There should be some integer value in the JSON, int section.I can't parse as JSON as it is.

Also, if you are writing questions like this, it would be better to provide relevant information such as which "Google API", what type of volumeInfo is declared, and how the value is set after the API call.

"However, this time you have posted the error message well, so I think I can provide you with a solution for ""for now"" even if I have some questions."

Most importantly, this part of the original JSON data:

"authors":["name"],

Did you notice that the value of "authors" is not "name" but ["name"]?

[] represents an array in JSON, so the value ["name"] is an array containing a single string.Not a string.

In the Could not cast value of type 'NSSingleObjectArrayI' (0x3b5244d0) to 'NSString' (0x3b52d0ac) of the error message, NSSingleObjectArrayI is a type of array, so it is important to say

You cannot cast from an array to a string

That's what they say.

If you avoid as! which causes the app to crash due to a slight misunderstanding, you should access it like this.

iflet authorities=volumeInfo?["authors"]as?[String] instead of {//<-`String`
    print (authors)
} else{
    print("authors cannot be an Array of String")
}

In today's Swift, it is common to use Codable for such JSON pars.If the code is written for learning, we recommend that you rewrite it to use Codable now.


2022-09-29 21:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.