Question

I have an interesting problem where my JSON being returned for the same URI call, can be slightly different based on the user's Id. I don't know all the combinations of the differences as things could change over time. For example three different requests to same URL could return these three different JSON representations.

{ "success":true, "total":1, "list":[{
    "uid":"24",
    "firstname":"Richard",
    "question1":"Y"}
]}

{ "success":true, "total":1, "list":[{
    "uid":"25",
    "firstname":"Fred",
    "question2":"Yes"}
]}

{ "success":true, "total":1, "list":[{
    "uid":"26",
    "firstname":"Bob",
    "surname":"Wilde",
    "question3":"Cat"}
]}

Note the first call contains Question1 the second call contains Question2 and the third call contains surname and Question3.

The code to deserialize looks like this:-

var result = client.Execute<ResultHeader<Customer>>(request);


public class ResultHeader<T>
{
    public bool Success { get; set; }
    public int Total { get; set; }
    public List<T> List { get; set; }
}

public class Customer
{
   public string Firstname { get; set; }  //This is always returned in the JSON

   //I am trying to get this...
   public Dictionary<string, string> RemainingItems { get; set; }
}

What I am trying to do is to have either return a dictionary collection of ALL things contained in list that are are not common and have not been deserialized or failing that a dictionary of ALL things contained in list. Some assumptions are that all values inside list can be treated as strings if need be.

Is this possible using RESTSharp ? I don't want to use dynamic as at compile time I won't know all possibilities. Basically once I have a dictionary I can loop and map where I need to at run time.

Was it helpful?

Solution

I would do a intermediate step:

var resultTmp = client.Execute<ResultHeader<Dictionary<string,string>>>(request);
var finalResult = AdaptResult(resultTmp);

Where AdaptResult can be implemented as follows:

static ResultHeader<Customer> AdaptResult(
                         ResultHeader<Dictionary<string, string>> tmp)
{
    var res = new ResultHeader<Customer>();
    res.Success = tmp.Success;
    res.Total = tmp.Total;
    res.List = new List<Customer>();
    foreach (var el in tmp.List)
    {
        var cust = new Customer();
        cust.Firstname = el["Firstname"];
        cust.RemainingItems = 
            el.Where(x => x.Key != "Firstname")
              .ToDictionary(x => x.Key, x => x.Value);
        res.List.Add(cust);
    }
    return res;
}

Of course the adapting method will contain your check logic (e.g. fail if all questions are in the dictionary etc.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top