0

I have a situation where I need to parse JSON that is sometimes an array and other times a single variable. So I'm unsure how to create my C# classes.

There is a single screen item, but question and answer are sometimes an array.

I'm using Newtonsoft.Json

JSON EXAMPLE 1:

{
  "screen": {
    "id": "39968400",
    "name": "Role Requirements for Job 39967376",
    "successful": "True",
    "question": {
      "id": "1",
      "type": "Text",
      "text": "What is your residential city and postcode?",
      "answer": {
        "id": "1",
        "selected": "True",
        "text": "Brisbane, 3000"
      }
    }
  }
}

JSON EXAMPLE 2:

{
    "screen": {
        "id": "98726",
        "name": "Copy of Simple Screening Standard Form 6900",
        "successful": "True",
        "question": [
            {
            "id": "440562",
            "type": "MultipleChoiceOneAnswer",
            "text": "What is your current work status?",
            "answer": [
                {
                    "id": "1",
                    "selected": "True",
                    "text": "Looking"
                },
                {
                    "id": "2",
                    "text": "Not Looking"
                }
            ]
            },
            {
            "id": "440563",
            "type": "MultipleChoiceOneAnswer",
            "text": "When are you available to begin employment?",
            "answer": [
                {
                    "id": "1",
                    "selected": "True",
                    "text": "Now"
                },
                {
                    "id": "2",
                    "text": "2 weeks"
                }
            ]
            }
        ]
    }
}
Sisir
  • 4,584
  • 4
  • 26
  • 37
Ross Kelly
  • 477
  • 1
  • 6
  • 23
  • Have you considered that an array can contain a single element and still be a valid array – Sisir Sep 18 '19 at 04:59
  • yes. i've tried using an array, but I get an error: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List – Ross Kelly Sep 18 '19 at 05:01
  • 1
    Declare your properties than can either be a single object or array as a `List`, then mark those properties with `[JsonConverter(typeof(SingleOrArrayConverter))]` where `T` is a class representing the item, as shown in the linked duplicate. That will solve the problem. – Brian Rogers Sep 18 '19 at 05:18
  • 1
    Here is a working demo in case you need it: https://dotnetfiddle.net/pTEgZS – Brian Rogers Sep 18 '19 at 05:33
  • 1
    @BrianRogers thanks for the feedback and link. I read the duplicate question and answer, and I now understand what to do. – Ross Kelly Sep 18 '19 at 06:27

0 Answers0