-1

I need to parse in Swift a data structure similar to this (based on a JSON):

[
  {
   "Name": "uniquename",
   "Value": "John"
  }, 
  {
   "Name": "locale",
   "Value": "UK"
  }, 
]

I stored this node in a struct like this

struct Rowset : Decodable {
  var row: LoggedUserSession

  init(loggedUser: [LoggedUserSession]){
    self.row = loggedUser[0]
  }

  enum CodingKeys: String, CodingKey{
    case row = "Row"
  }
}

I prepared a similar struct to all the data I need to extract from the array but I don't know how to iterate on that and return the value when the name string match my case.

struct LoggedUserSession : Decodable {
  var username: String;
  var locale: String;


  init(username: String, locale: String) {
    // In JS I would embedd an iterator here and return the values 
    self.username = username
    self.locale = locale
  }

  enum CodingKeys: String, CodingKey {
    case username = "uniquename"
    case locale = "locale"
  }
}
Nicola Bertelloni
  • 333
  • 1
  • 3
  • 17

1 Answers1

0

If I understand what you are saying correctly, you want to parse an array of LoggedUserSession JSONs into a swift array of LoggedUserSessions. If that's the case, then you're almost there.

For completeness, I'm going to interpret the JSON you posted as follows so that it is valid:

{"loggedUserSessions":
  [
    {
     "uniquename": "John",
     "locale": "UK"
    }
  ]
}

Your LoggedUserSession object is implemented correctly, so now all you need is the array parsing part. You can do that with the following struct:

struct SessionList: Decodable {

  let sessions: [LoggedUserSession]

}

Calling this with JSONDecoder and your JSON data should serialize your list into an array that you can access via the SessionList's sessions property.

rpecka
  • 1,168
  • 5
  • 17