1

I'm coming today for a little problem where I'm stuck.

I'm making a c# xamarin app and this one receives messages (JSON) from my server. The thing is, this message contains 2 fixes variables (String Descrption, Int StatusId). However, a third value is put in this message. This value can be either an object or a range of object. It means that my class can be the two following possibilities:

Case 1 -> I got an object as Result

public class Result
{
    public string name { get; set; }
}

public class RootObject
{
    public string Description { get; set; }
    public Result Results { get; set; }
    public int StatusId { get; set; }
}

Case 2 -> I got a list of results as List<Result>

public class Result
{
    public string name { get; set; }
}

public class RootObject
{
    public string Description { get; set; }
    public List<Result> Results { get; set; }
    public int StatusId { get; set; }
}

Of course, it's all time a Result object which is get, however, it can be either alone or such as a list.

How can I deserialize this object JSON into the right class if this object can have two possibilities of unserialization?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Emixam23
  • 3,854
  • 8
  • 50
  • 107
  • 4
    http://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n Check this answer where a custom converter is used. – Christian Phillips Jun 06 '16 at 11:41
  • 3
    I would work towards making the code always return a collection of results. It shouldn't matter for UI if there is one item in the collection or many – DanielS Jun 06 '16 at 11:46
  • 2
    I don't understand why you'd make the server send it as a single object rather than a Collection containing a single object, way more simple approach. – Toxicable Jun 06 '16 at 12:01
  • You're right Toxicable and DanielS, I will think about it. Thank all for your answers. christiandev your answer is what I searched ! – Emixam23 Jun 06 '16 at 12:15

0 Answers0