-1

I apologize if this is a duplicate, but none of the related answers I saw had JSON similar to the format I'm dealing with. I'm consuming an API response that has the following JSON format:

{
  "KnownPropName": [
  {
    "DynamicPropName": [
    {
      "KnownProp1": "value",
      "KnownProp2": "value"
    },
    {
      "KnownProp1": "value",
      "KnownProp2": "value"
    }]
  }]
}

I know the names of the parameters for each object except for "DynamicPropName", which I cannot know ahead of time.

I have the below classes setup:

private class TestResponse
{
    public TestOuter[] KnownPropName { get; set; }
}
private class TestOuter
{
    public TestInner[] TestInners { get; set; }
}
private class TestInner
{
    public string KnownProp1 { get; set; }
    public string KnownProp2 { get; set; }
}

If I change the property name "TestInners" to "DynamicPropName" everything deserializes with no issues. However, since I will not know the actual property name ahead of time I need to somehow have this work when "TestInners" does not match the corresponding property name.

I don't believe I can use a dictionary because the arrays don't contain string keys, but instead objects.

I know I can use a custom converter to solve this, but I'd like to know if it is at all possible without using one. Is there a way to have JSON deserialize based on the order of the parameters instead of depending on the name?

Andrew Simon
  • 148
  • 7
  • This doesn't help? - https://stackoverflow.com/questions/15253875 – Rand Random Jul 25 '19 at 16:19
  • That answer was in the list of related questions and would be the closest to solving it without using a converter. I was curious if there was another way to structure the class to have it serialized without any other manipulation, but from the looks of it I'll just go with this solution. Thanks! – Andrew Simon Jul 25 '19 at 17:00

1 Answers1

0

From the JSON sample you've given, I don't see why a dictionary wouldn't work here. As I see it, KnownPropName is actually an array of dictionaries where each dictionary has string keys, representing the dynamic property name(s), and values which are arrays of TestInner objects.

In other words, declare your classes like this:

private class TestResponse
{
    public Dictionary<string, TestInner[]>[] KnownPropName { get; set; }
}

private class TestInner
{
    public string KnownProp1 { get; set; }
    public string KnownProp2 { get; set; }
}

You don't need the TestOuter class.

Fiddle: https://dotnetfiddle.net/MHOYwm

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300