Search code examples
c#json.netparsingjson.net

Deserialize a lot of properties from JSON


Here's an example of the JSON file:

{
    "Object": {
        "series": {
            "transformation": "",
            "source": "series",
            "default": ""
        },
        "latitude": {
            "transformation": "",
            "source": "lat",
            "default": ""
        },
        "longitude": {
            "transformation": "",
            "source": "long",
            "default": ""
        }
   }
}

My current class for deserializing with JsonConvert.DesirializeT()

internal class ImportedObjects
{
        [JsonProperty("Object")]
        public ImportedSubProperties ImportedObject { get; set; }

        internal class ImportedSubProperties : ImportedObjects
        {
            [JsonProperty("series")]
            public ImportedProperties series { get; set; }

            [JsonProperty("latitude")]
            public ImportedProperties latitude { get; set; }

            [JsonProperty("longitude")]
            public ImportedProperties longitude { get; set; }
        }
}

internal class ImportedProperties
{
        public string Transformation { get; set; }
        public string Source { get; set; }
        public string Default { get; set; }
}

Current code for parsing:

using (StreamReader r = new StreamReader(file))
{
    string json = r.ReadToEnd();
    MappingObjects = JsonConvert.DeserializeObject<ImportedObjects>(json);
}

Everything's looking fine when there are only 3 properties (series, latitude, longitude) but in the actual file there are at least 50 properties after "longitude" (X, Y, Size,...). My question: is it possible to use deserialization without resorting to creating additional 50 properties? Preferably storing everything directly into a dictionary.


Solution

  • You can use Dictionary<>.

    internal class ImportedObjects
    {
         public Dictionary<string,ImportedProperties> Object { get; set;}
    }
    
    internal class ImportedProperties
    {
            public string Transformation { get; set; }
            public string Source { get; set; }
            public string Default { get; set; }
    }