Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I deserialize to a class and have extra JSON properties go into a JObject on that class?

Tags:

json

c#

json.net

Let's assume we have the following JSON:

{ 
    "a": 10,
    "b": "foo",
    "c": 30,
    "d": "bar",
}

and the C# class:

class Stuff 
{
    public int A { get; set; }
    public string B { get; set; }
    public JObject Others { get; set; }
}

Is there an easy way to make the deserialization of the JSON above populate members A and B with the values of a and b and put the values of c and d as JProperties in the Others JObject?

like image 877
jool Avatar asked Sep 15 '25 16:09

jool


1 Answers

Yes, you can do this easily using Json.Net's "extension data" feature. You just need to mark your Others property with a [JsonExtensionData] attribute and it should work the way you want.

class Stuff 
{
    public int A { get; set; }
    public string B { get; set; }
    [JsonExtensionData]
    public JObject Others { get; set; }
}

Demo:

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        { 
            ""a"": 10,
            ""b"": ""foo"",
            ""c"": 30,
            ""d"": ""bar"",
        }";

        var stuff = JsonConvert.DeserializeObject<Stuff>(json);

        Console.WriteLine(stuff.A);
        Console.WriteLine(stuff.B);
        Console.WriteLine(stuff.Others["c"]);
        Console.WriteLine(stuff.Others["d"]);
    }
}

Output:

10
foo
30
bar

Fiddle: https://dotnetfiddle.net/6UVvFI

like image 97
Brian Rogers Avatar answered Sep 17 '25 06:09

Brian Rogers