2

Somebody made a very poor design decision and can deliver me a JSON that has an "exceptional" structure. To simplfy the problem:

{
    "messed-up": "string"
}

{
    "messed-up": { "nested": "value" }
}

Basically a field (very deeply hidden in my case) can be either a string or a more complex object. I need to create such a class structure that would allow me to:

  • Perform serialization / deserialization
  • Generate schema

Thus I would need something like this:

public class NotFunny
{
    [JsonProperty("messed-up", NullValueHandling = NullValueHandling.Ignore)]
    public string messedUp;

    [JsonProperty("messed-up", NullValueHandling = NullValueHandling.Ignore)]
    public Alternative messedUpAlternative;
}

public class Alternative
{
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string nested;
}

However, for obvious reasons, this cannot work. My question is: how to deal with this sad case?

Any help greatly appreciated!

ebvtrnog
  • 4,167
  • 4
  • 31
  • 59

1 Answers1

1

You could try to use dynamic type for this purposes.

Sample

My Sample with Newtonsoft.Json:

using Newtonsoft.Json.Linq;

dynamic data1 = JObject.Parse(str1);

if (data1.messed_up is JValue)
    Console.WriteLine(data1.messed_up);

if (data1.messed_up is JObject)
    Console.WriteLine(data1.messed_up.nested);
Community
  • 1
  • 1
Boris Sokolov
  • 1,723
  • 4
  • 23
  • 38