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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With