Esempio n. 1
0
        public static void JsonNetDeserializeWithoutType()
        {
            var testObj = TestObj.GetDefault();
            var path    = @"C:\temp\TestObj.json";
            // wrap with type name so we know what type to deserialize to
            var outputObj = new Dictionary <string, object> {
                { "CSharpSnippets.Serialization.TestObj", testObj }
            };

            File.WriteAllText(path, JsonConvert.SerializeObject(outputObj, Formatting.Indented));

            var json = File.ReadAllText(path);
            // the top level type must be known, otherwise we can't traverse through it
            var inputObj = (Dictionary <string, JObject>)JsonConvert.DeserializeObject(json, typeof(Dictionary <string, JObject>));

            foreach (var kv in inputObj)
            {
                var typename = kv.Key;
                var type     = Type.GetType(typename);
                var typedObj = kv.Value.ToObject(type);
                Console.WriteLine(typedObj);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Serialize a class to file, then read it back
        /// </summary>
        public static void PackagingExample()
        {
            var testObj = TestObj.GetDefault();

            var packPath = @"C:\temp\blahpack.pack";

            using (var fileStream = new FileStream(packPath, FileMode.Create))
            {
                using (var packer = new ClassDataPacker(fileStream))
                {
                    packer.WriteEntity(testObj, x => x.Name);
                }
            }

            using (var pack = ClassDataPacker.OpenPack(packPath))
            {
                foreach (var part in pack.ListParts())
                {
                    Console.WriteLine(part.Uri);
                }
                var deserializedObj = pack.GetEntity <TestObj>("A_name");
                Console.WriteLine("Deserialized TestObj: " + deserializedObj);
            }
        }