Home > other >  JSON object to String in Swift
JSON object to String in Swift

Time:05-04

I have spend a lot of time googling and I could not get a solution to work so I hope someone can help me.

I have a string called user which is of type: < hit>JSON. I can get information out of it by using:

user.object["displayname"] ?? ""

This works fine however it gives me the result between "". So if someones displayname is stackoverflowuser it will give me: "stackoverflowuser". Is there a way to get this as a string without the ""?

Edit:

I use the following API: https://www.algolia.com/doc/api-reference/api-methods/search/#examples.

This is my code to get the user object:

index.search(query: "\(searchtext)") { result in
   if case .success(let response) = result {
      for user in response.hits {
         let resultDisplayname = "\(user.object["displayname"] ?? "")"

      }
   }
 }

The resultDisplayname is an example of a variable that I want to turn into a String.

CodePudding user response:

let's assume your JSON is like this format

{
    "displayname": "chrispv",
    "age": 30
}

Create a swift object to represent it

struct Person: Decodable {
    let displayname: String
    let age: Int
}

Then execute your search query using object above

index.search(query: "\(searchtext)") { result in
    if case .success(let response) = result {
        do {
            let persons: [Person] = try response.extractHits()
            for person in persons {
                print(person.displayname)
            }
        } catch let error {
            print("Decoding error")
        }
    }
}
  • Related