2021年3月29日星期一

Using Codable to decode json with attribute having different types

So this is the response structure that I have.

The same identifier attribute, can have a data associated with it that can be a list of other objects. The outermost table is list of other view types and the inner table is list of rows, if that makes sense.

{    "identifier": "table",    "data": [      {        "identifier": "top_view",        "data": [          {            "value": "this is top header type view"          }        ]      },      {        "identifier": "table",        "data": [          {            "value": "this is a first row in a table"          },          {            "value": "this is a second row in a table"          },          {            "value": "this is a third row in a table"          }        ]      },      {        "identifier": "bottom_view",        "data": [          {            "value": "this is a footer type view"          }        ]      }    ]  }  

Can I use swifts Codable to decode this in anyway? Solutions for this type of decoding generally involve having an enum around differentdata and using this to inject the correct type associated with it. But in this case, the identifier is the same.

Let me know if I need to add in more details.

Edit 1 - Well, I am trying to build a new app that has a backend driven UI. This is just the response of a screen within the app. 
To explain more about the json - The outermost table is a tableview that can have 3 cells - the first one being the top header, second a table(that again has 3 cells that each consists of label) and the third is a bootom footer (Not to be confused with a tableviews default header footer).

I understand that the json might be flawed in itself but initially I had hoped that it would work by employing a nested json structure (hence the use of same data key) The value of data in this case can change across different components.

enter image description here

https://stackoverflow.com/questions/66847554/using-codable-to-decode-json-with-attribute-having-different-types March 29, 2021 at 08:52AM

没有评论:

发表评论