I haven't written any code yet but I have a JSON which I want to get a specific block of data from to display on a very rudimentary view. I just want to grad a block of data that is nested in a JSON. Is there method for doing such a thing simply with swiftui? Im a beginner at Swiftui.
There are multiple ways to access specific blocks of data from JSON data. If you fetch your JSON object from an API, you'll likely need to decode it ( Data
type to custom type).
There is a great library to access specific parts of a JSON object which is called SwiftyJSON . They provide a few examples like this one:
let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
//Now you got your value
}
You have to serialize your JSON object and afterwards, you can access a specific block using:
if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],
let user = statusesArray[0]["user"] as? [String: Any],
let username = user["name"] as? String {
// Finally we got the username
}
The last method is to create a data model and parse your JSON. To create your data model you can use an app called quicktype . You can then decode simply. Here's a link to show you how .
After decoding the data, you can parse it to an ObservableObject
and loop through it using a List
or aForEach
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.