1

I use an API that has JSON like this:

{
    id: 1,
    firstName: "test",
    lastName: "user",
    field26461: "abc123"
}

I have this C# class

{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

They continually add these custom fields. So after shipping my code, there may be a "field32123" in there with some value.

How can I make my code capture these extra fields?

Could I update my class to the following, and somehow have all the fields and their values go into a dictionary?

{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Dictionary<string,string> ExtraFields { get; set; }
}

XML has an [XmlAnyElement] attribute that you can use to capture such extra fields.

Christopher
  • 10,409
  • 13
  • 73
  • 97
  • Since you don't know the name or type of those extra fields other than names _should_ be a string, a dictionary/map is a good option – j1mbl3s Jun 03 '21 at 17:25
  • 2
    You can use [`JsonExtensionDataAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonextensiondataattribute) as shown in e.g. [Properties of extended dictionary won't show in serialization](https://stackoverflow.com/a/59524410/3744182) and [Is it possible to catch somehow the remainder of JSON data that didn't match any POCO properties while deserializing?](https://stackoverflow.com/a/63228977/3744182). – dbc Jun 03 '21 at 17:25
  • However it needs to be a `Dictionary` or `Dictionary`, and the actual object will end up being of type `JsonElement` even for primitive values. Does that answer your question? – dbc Jun 03 '21 at 17:28
  • I found the question asked previously. Do I delete mine? https://stackoverflow.com/questions/15253875/deserialize-json-with-known-and-unknown-fields – Christopher Jun 03 '21 at 18:14
  • Thanks @dbc, that worked – Christopher Jun 03 '21 at 18:15
  • 1
    @Chris - [that one](https://stackoverflow.com/questions/15253875/deserialize-json-with-known-and-unknown-fields) is tagged for Json.NET, you're asking about System.Text.Json. No need to delete. – dbc Jun 03 '21 at 18:17

0 Answers0