3

I have a class like this:

public class Event
{
            [JsonProperty(PropertyName = "_id")]
            public string Id { get; set; }
            [JsonProperty(PropertyName = "status"]
            public string Status { get; set; }
}

I am receiving JSON that looks like this:

[
    {
        "_id": 4,
        "status": "started"
    },
    {
        "_id": 117841261,
        "status": {
            "_statusid": 1,
            "date": "01.01.2015"
        }
    }
]

Please be aware: in the first object, the status field is a string. In the second object, it's an object. In my object it's a string property. I want to parse it whenever the status field is a string. I'm okay with skipping it when it's an object like in the second object.

I have tried changing the defaultValueHanding options in the JsonProperty attribute, but it didn't help. Is there any way to achieve this?

Leigh
  • 28,765
  • 10
  • 55
  • 103
Sefa
  • 8,865
  • 10
  • 51
  • 82
  • In the second object, status is an object, not an array. – xlecoustillier Dec 16 '14 at 13:18
  • 1
    This question is not a duplicate of the marked question because it is not asking about schema validation. However, I would argue it IS a duplicate of [How to deserialize a JSON property that can be two different data types using Json.NET](http://stackoverflow.com/q/20432166/10263) – Brian Rogers Dec 20 '14 at 21:55

1 Answers1

1

I have solved this problem chaging property type to dynamic. So it's deserializing everytime with no problem and i am using it only when i need it.

Now my model looks like this:

public class Event
{
            [JsonProperty(PropertyName = "_id")]
            public string Id { get; set; }
            [JsonProperty(PropertyName = "status"]
            public dynamic Status { get; set; }
}

As Brian Rogers pointed out, custom converter can be found here:

How to deserialize a JSON property that can be two different data types using Json.NET

Community
  • 1
  • 1
Sefa
  • 8,865
  • 10
  • 51
  • 82