4

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?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
jool
  • 1,491
  • 12
  • 14
  • possible duplicate of [Deserialize json with known and unknown fields](http://stackoverflow.com/questions/15253875/deserialize-json-with-known-and-unknown-fields) – t3z Dec 01 '14 at 12:07

2 Answers2

3

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

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

You would need to implement a JsonConverter for this. It provides full flexibility in terms of custom deserialization.

Implement your ReadJson method to traverse the input JSON using JsonReader and map its values to appropriate destination properties.

See here for full example.

t3z
  • 1,737
  • 12
  • 14
  • You have my +1 for the good answer. You may still turn this into an excelent answer if you include an example in the question itself - sometimes links get broken (when the external content ceases existing), but examples within the answer itself are always timeless. – Geeky Guy Dec 01 '14 at 03:55
  • Thanks, actually I discovered that there is a solution and implementation already [here on StackOverflow](https://stackoverflow.com/questions/15253875/deserialize-json-with-known-and-unknown-fields/15255330#15255330), so I marked this question as duplicate. – t3z Dec 01 '14 at 12:11