0

I am utilizing an api created by the makers of some software we use to generate forms on our website. These forms can have a variable number of questions/inputs. Looking at output from Swagger when imported to Visual Studio -> Paste JSON as Class, for one of the forms I get:

public class Source
{
    public DateTime SubmittedAt { get; set; }
    public int UserID { get; set; }
    public int FormId { get; set; }
    public int Id { get; set; }
    public Data Data { get; set; }
}

public class Data
{
    public string _1 { get; set; }
    public string _2 { get; set; }
    public string _3 { get; set; }
    public string _4 { get; set; }
}

Where Data is the list of questions.

But if I were to look at another form with a different number of questions, this class would be either shorter or longer. So I guess I'm curious how you would model a class based on json that returns a variable number of items. I'm pretty new to both json and c#.

Per below request, this is what the json that is returned looks like. In this example, there are four questions "Is this a question or a comment?", "First Name", "Last Name", "Enter your question or comment."

{
  "Source": [
    {
      "SubmittedAt": "2021-03-17T08:52:32.16",
      "UserID": 24601,
      "FormId": 420,
      "Id": 777,
      "Data": {
        "1": "Comment",
        "2": "First Name",
        "3": "Pseudonym",
        "4": "Blah blah blah blah.."
      }
    }
  ]
}
Roger Asbury
  • 351
  • 1
  • 4
  • 13
  • 4
    If it's all strings you could put it in a dictionary – HandsomeRob Mar 22 '21 at 23:31
  • 1
    It would be helpful if you could include the actual JSON rather than just the Visual Studio interpretation of it. – Jack A. Mar 23 '21 at 00:06
  • 1
    You can deserialize into a `public Dictionary Data { get; set; }` as shown in [How can I parse a JSON string that would cause illegal C# identifiers?](https://stackoverflow.com/a/24536564/3744182) or [Create a strongly typed c# object from json object with ID as the name](https://stackoverflow.com/a/34213724/3744182). If using [tag:json.net] you can use a `Dictionary`. In fact I think this is a duplicate of those, agree? – dbc Mar 23 '21 at 02:40
  • Those links were perfect, thanks much and sorry for the repeated question! – Roger Asbury Mar 23 '21 at 21:27

0 Answers0