4

I have a defined C# object based off a very complex JSON I'm getting from a third party API. Here's a piece of it:

{"alarmSummary":"NONE"}

The corresponding property in C# would be:

public string alarmSummary {get; set;}

And I would get this converted by using my typical JSONConvert from JSON.NET:

var alarms = JSONConvert.DeserializeObject<MyClass>(jsonString); 

However, the API will put alarms in this format, as an array, and "NONE" when there aren't any as a string:

{"alarmSummary" : ["AHHH Something went wrong!!", "I'm on fire!!"]}

Which means in C# it would need to be:

public string[] alarmSummary {get; set;}

If I could, I would just have the JSONConvert deserialize the "NONE" string into an array of just one entry. Is there a way to set conditions on this property, or will I have to take the whole complex JSON string and hand convert it?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Kat
  • 2,460
  • 2
  • 36
  • 70

2 Answers2

3

This one should be easy - you can set your alarmSummary as object and then have separate property that evaluates alarmSummary and returns null or array depending on the value.

    public object alarmSummary { get; set; }

    protected string[] alarmSummaryCasted
    {
        get
        {
            if (alarmSummary is String)
                return null;
            else
                return (string[]) alarmSummary;
        }
    }
nikib3ro
  • 20,366
  • 24
  • 120
  • 181
  • What method would you use to deserialize? – Edin Mar 03 '16 at 21:09
  • @Edin I was suggesting this if he has `alarmSummary` as property on POCO class and deserializes instance of that class (this is what I do with ServiceStack.Text JSON library). If he is directly deserializing to variable, what you suggest in your answer is better, plus it also uses specific functionality of Json.Net library. – nikib3ro Mar 03 '16 at 21:14
1

If you are expecting only those two combinations, you could make use of the dynamic keyword and check deserialized object:

string json = "{\"alarmSummary\":\"NONE\"}";
//string json = "{\"alarmSummary\" : [\"AHHH Something went wrong!!\", \"I'm on fire!!\"]}";

string[] alarmSummary;
dynamic obj = JsonConvert.DeserializeObject(json);
if (obj.alarmSummary.Type == JTokenType.Array)
   alarmSummary = obj.alarmSummary.ToObject<string[]>();
else
   alarmSummary = new[] { (string)obj.alarmSummary.ToObject<string>() };
Edin
  • 1,476
  • 11
  • 21