Home > Mobile >  Desirialize a lot of properties from JSON
Desirialize a lot of properties from JSON

Time:09-26

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.

CodePudding user response:

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; }
}

CodePudding user response:

I would recommend that you pass the StreamReader to JsonTextReader thats more efficient than using ReadToEnd.

JsonSerializer serializer = new JsonSerializer();
using (StreamReader r = new StreamReader(file))
{
    using( JsonTextReader reader = new JsonTextReader( r ) )
    {
        MappingObjects = serializer.Deserialize<ImportedObjects>( reader );
    }
}
  • Related