Search code examples
c#jsondatacontract

Placing undefined data members names into generic Diction<string, object> when parsing JSON


I have this JSON (actually Swagger) :

{
  "swagger": "2.0",
  "info": {
    "version": "2.0",
    "name": "TheName",
    "description": "No description"
  }
  "somethingElse" : "xyz"
}

I am using Newtonsoft.JSON. I defined my object:

public class WebService
{
    public string swagger;
    public Dictionary<string, object> AllOthers;
}

As you can see I have not defined "info" or "somethingElse" objects as members. Rather, I want this to get placed into the generic AllOthers dictionary

When I call

var ws = Newtonsoft.Json.JsonConvert.DeserializeObject<WebService>(swaggerJSON);

ws will now correctly contain the swagger version number string, but AllOthers will contain null. I want AllOthers to contain a entires for name and description, and the payloads to by stored in a generic object.

How is this achieved, or can it not be easily?

Thanks


Solution

  • There is an attribute for this [JsonExtensionData]. Mark your dictionary with this attribute:

    public class WebService
    {
      public string swagger;
      [JsonExtensionData]
      public Dictionary<string, object> AllOthers;
    }
    
    var ws = Newtonsoft.Json.JsonConvert.DeserializeObject<WebService>(json);
    

    I hope this helps! cheers.