JSON decoding help needed

Hi there,

since I have only few experiences with this kind of tasks, could anyone help me parsing the following JSON I get in response from an API call?

{
   {
  "members": [
    {
      "link": "http://Server-IP/rest/items/item1",
      "state": "OFF",
      "stateDescription": {
        "pattern": "%s",
        "readOnly": false,
        "options": [
          
        ]
      },
      "type": "Switch",
      "name": "item1",
      "label": "labe1",
      "tags": [
        
      ],
      "groupNames": [
        "group1"
      ]
    },
    {
      "link": "http://Server-IP/rest/items/item2",
      "state": "OFF",
      "stateDescription": {
        "pattern": "%s",
        "readOnly": false,
        "options": [
          
        ]
      },
      "type": "Switch",
      "name": "item2",
      "label": "label2",
      "tags": [
        
      ],
      "groupNames": [
        "group1"
      ]
    }
   
  ],
  "groupType": "Switch",
  "function": {
    "name": "EQUALITY"
  },
  "link": "http://Server-IP/rest/items/group1",
  "state": "OFF",
  "editable": false,
  "type": "Group",
  "name": "group1",
  "label": "group_label",
  "tags": [
    "Switchable"
  ],
  "groupNames": [
    
  ]
}

I need to parse the following values and key: "name": "item1" - "state": "OFF" for every single object of the array (I have 30 of them) but I definitely can't understand how to do since keys and values are repeated...

Thank You
Luca

I recommend using the Decodable protocol for this.

To start, make a basic struct containing the information you want, which conforms to Decodable. If the keys and structure map perfectly, you can use the default implementation to decode an Array of that type. If not (you may want to use an enumeration for state, for instance, or call the name id instead for use with Identifiable), you have to implement it manually. That is still quite straightforward, don’t worry.

That JSON sample isn’t actually valid, so I’m not sure what the structure is. I’m also not sure what you mean when you say keys are repeated. Do you have any specific questions beyond that?

Terms of Service

Privacy Policy

Cookie Policy