Is it possible to deserialize a class and get additional JSON properties in JObject in that class?
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 do JSON deserialization over placeholders A
and B
values A
and B
and put the values c
and d
as JProperties in the Others
JObject?
source to share
To do this, you need to implement JsonConverter . It provides complete flexibility in terms of custom deserialization.
Implement the ReadJson method to traverse the input JSON using the JsonReader and map its values to the appropriate destination properties.
See here for details .
source to share
Yes, you can do it easily using Json.Net "extension data". You just need to mark your property with an Others
attribute [JsonExtensionData]
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
source to share