Search code examples
c#.netjson.netrefit

Parse weird response with refit


I have an API response which is an array containing an object and an array like below:

[
  {
    "questions": [
      {
        "type": 3
      },
      {
        "type": 7
      }
    ]
  },
  []
]

I tried parsing like this but got no luck:

public class TableDetailResponse
    {
        public QuestionTable Table { get; set; }
        public List<object> Errors { get; set; }
    }

public class QuestionTable
    {
        [JsonProperty("questions")]
        public List<Question> Questions { get; set; }
    }

public class Question
    {
        [JsonProperty("type")]
        public int Type { get; set; }
    }

using Refit;


public interface SOJOSurveyService
    {
        [Get("/survey/{id}")]
        Task<TableDetailResponse> QueryQuestionsByFlow([AliasAs("id")] string questionID);
    }

How to parse the above json?


Solution

  • Your root result is actually JSON array which has elements of different types. Assuming that you are using Newtonsoft Json.NET (based on the tags) you have basically two options - "dynamic" deserialization or custom converter. First option would be a bit easier, to get you started:

    Task<JArray> QueryQuestionsByFlow(...);
    

    And then deserialize:

    var js_str = """
    [
      {
        "questions": [
          {
            "type": 3
          },
          {
            "type": 7
          }
        ]
      },
      []
    ]
    """;
    
    var tokens = JsonConvert.DeserializeObject<JArray>(js_str);
    
    var questionTable = (tokens[0] as JObject) // or iterate and check the node type - tokens[1].Type == JTokenType.Object ...
        .ToObject<QuestionTable>();
    Console.WriteLine(questionTable.Questions.Count); // prints "2"
    

    Custom converter approach will be doing something similar.

    But I would recommend looking into fixing the called API. While the JSON itself is valid, the format is definitely not consumer-friendly.