1

I have some JSON that looks like this:

{
    "data": {
        "storePurchase": {
            "id": "d4f7475a-0023-416f-b6a1-257659a341f5",
        }
    }
}

I also have some JSON that looks like this:

{
    "data": {
        "userInfo": {
            "username": "...."
        }
    }
}

How can I write a deserializer to handle any object type that might appear under data. I know the structure of the sub-objects under data upfront, so I don't need dynamics.

I have tried this so far:

    public class BaseData<T>
    {
        public T Data { get; set; }
    }

    [JsonObject("userInfo")]
    public class Me
    {
        [JsonProperty("username")]
        public string Username { get; set; }
    }


    public class BootstrapQueryResponse
    {
        [JsonProperty("data")]
        public BaseData<Me> BaseData { get; set; }
    }

    [TestMethod]
    public void Test()
    {
        string json = @"{
                ""data"": {
                    ""userInfo"": {
                        ""username"": ""....""
                    }
                }
            }";

        BootstrapQueryResponse s = JsonConvert.DeserializeObject<BootstrapQueryResponse>(json);
    }

However, my object s is returning null for the data property.

dbc
  • 104,963
  • 20
  • 228
  • 340
Sam
  • 602
  • 9
  • 21
  • 1
    Looks like a duplicate of [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/3744182), agree? – dbc Mar 20 '22 at 00:30
  • 1
    Incidentally, your data model has an extra level of `{"Data:" { } }` nesting. I.e. if I serialize an instance of `BootstrapQueryResponse` I get `{"data":{"Data":{"username":"...."}}}`, see https://dotnetfiddle.net/NS14G0. That likely explains the `null` value you are seeing. – dbc Mar 20 '22 at 03:20

1 Answers1

0

@dbc is right, try:

public class BaseData<T>
{
    [JsonProperty("data")] // <-- this goes here
    public T Data { get; set; }
}

var s = JsonConvert.DeserializeObject<BaseData<Me>>(json)
beautifulcoder
  • 10,832
  • 3
  • 19
  • 29