// -----------------------------------------------------------------
        /// <summary>
        ///
        /// </summary>
        // -----------------------------------------------------------------
        private static RequestBase DeserializeFromReader(JsonReader reader)
        {
            List <JsonConverter> clist = new List <JsonConverter>();

            clist.Add(new Vector3Converter());
            clist.Add(new UUIDConverter());
            clist.Add(new QuaternionConverter());

            TypeNameSerializationBinder binder   = new TypeNameSerializationBinder("{0}");
            JsonSerializerSettings      settings = new JsonSerializerSettings();

            settings.Binder           = binder;
            settings.TypeNameHandling = TypeNameHandling.Objects;
            settings.Converters       = clist;

            JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
            object         result         = jsonSerializer.Deserialize(reader, null);

            if (result == null)
            {
                return(null);
            }

            return((RequestBase)result);
        }
Example #2
0
        static void Main(string[] args)
        {
            var binder     = new TypeNameSerializationBinder("ConsoleApplication.{0}, ConsoleApplication");
            var toserilize = new ClassToSerializeViaJson();

            toserilize.CollectionToSerialize.Add(new TestClassThatImplementsTestInterface1()
            {
                Guid = Guid.NewGuid().ToString(), Something1 = "Some1"
            });
            toserilize.CollectionToSerialize.Add(new TestClassThatImplementsTestInterface2()
            {
                Guid = Guid.NewGuid().ToString(), Something2 = "Some2"
            });

            string json = JsonConvert.SerializeObject(toserilize, Formatting.Indented, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Binder           = binder
            });
            var obj = JsonConvert.DeserializeObject <ClassToSerializeViaJson>(json, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Binder           = binder
            });

            Console.ReadLine();
        }
        // -----------------------------------------------------------------
        /// <summary>
        ///
        /// </summary>
        // -----------------------------------------------------------------
        public byte[] SerializeToBinaryData()
        {
            List <JsonConverter> clist = new List <JsonConverter>();

            clist.Add(new Vector3Converter());
            clist.Add(new UUIDConverter());
            clist.Add(new QuaternionConverter());

            // The type name handling is pretty verbose here, but makes deserialization
            // symmetric, its enough information to figure out how to handle the structures
            TypeNameSerializationBinder binder   = new TypeNameSerializationBinder("{0}, {1}");
            JsonSerializerSettings      settings = new JsonSerializerSettings();

            settings.Binder           = binder;
            settings.TypeNameHandling = TypeNameHandling.Objects;
            settings.Converters       = clist;

            JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);

            MemoryStream ms   = new MemoryStream();
            BsonWriter   bson = new BsonWriter(ms);

            jsonSerializer.Serialize(bson, this, null);
            return(ms.ToArray());
        }
Example #4
0
    private static T DeserializeObjectFromJson(string json)
    {
        var binder = new TypeNameSerializationBinder("");
        var obj    = JsonConvert.DeserializeObject <T>(json, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto,
            Binder           = binder
        });

        return(obj);
    }
        public static HttpConfiguration UseSimpleJsonMediaContent(this HttpConfiguration configuration, params Assembly[] assembliesForTypeNameHandling)
        {
            var binder = new TypeNameSerializationBinder("{0}");

            binder.Assemblies.AddRange(assembliesForTypeNameHandling);

            var settings = new JsonSerializerSettings {
                Formatting          = Formatting.Indented,
                ContractResolver    = new CamelCasePropertyNamesContractResolver(),
                NullValueHandling   = NullValueHandling.Ignore,
                SerializationBinder = binder
            };

            configuration.Formatters.JsonFormatter.SerializerSettings = settings;
            return(configuration);
        }
        // -----------------------------------------------------------------
        /// <summary>
        ///
        /// </summary>
        // -----------------------------------------------------------------
        public string SerializeToString()
        {
            List <JsonConverter> clist = new List <JsonConverter>();

            clist.Add(new Vector3Converter());
            clist.Add(new UUIDConverter());
            clist.Add(new QuaternionConverter());

            // The type name handling is pretty verbose here, but makes deserialization
            // symmetric, its enough information to figure out how to handle the structures
            TypeNameSerializationBinder binder   = new TypeNameSerializationBinder("{0}, {1}");
            JsonSerializerSettings      settings = new JsonSerializerSettings();

            settings.Binder           = binder;
            settings.TypeNameHandling = TypeNameHandling.Objects;
            settings.Converters       = clist;

            return(JsonConvert.SerializeObject(this, Formatting.None, settings));
        }
Example #7
0
        /// <summary>
        /// Saves the current data to the cache directory for loading later
        /// </summary>
        public static async void SaveCurrentData()
        {
            var binder = new TypeNameSerializationBinder("SpeechingShared.{0}, SpeechingShared");
            string dataString = JsonConvert.SerializeObject(Session, Formatting.Indented, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Binder = binder
            });

            if (_saveFile == null)
            {
                if (await Root.CheckExistsAsync("offline.json") != ExistenceCheckResult.FileExists)
                {
                    await Root.CreateFileAsync("offline.json", CreationCollisionOption.ReplaceExisting);
                }
                _saveFile = await Root.GetFileAsync("offline.json");
            }

            await Utils.GetSemaphore("offline.json").WaitAsync();
            try
            {
                // Make sure only 1 thread is allowed here at a time :)
                await _saveFile.WriteAllTextAsync(dataString);
            }
            finally
            {
                Utils.GetSemaphore("offline.json").Release();
            }
        }
Example #8
0
        /// <summary>
        /// Attempts to load existing data stored in a local file.
        /// </summary>
        /// <returns>true if successful, false if a request to the server is needed</returns>
        public static async Task<bool> TryLoadExistingData()
        {
            if (Rand == null) Rand = new Random();

            try
            {
                if ((await Root.CheckExistsAsync("offline.json")) == ExistenceCheckResult.FileExists)
                {
                    IFile json = await Root.GetFileAsync("offline.json");

                    var binder = new TypeNameSerializationBinder("SpeechingShared.{0}, SpeechingShared");
                    Session = JsonConvert.DeserializeObject<SessionData>(await json.ReadAllTextAsync(),
                        new JsonSerializerSettings
                        {
                            TypeNameHandling = TypeNameHandling.Auto,
                            Binder = binder
                        });
                    ServerData.StorageRemoteDir = "uploads/" + Session.CurrentUser.Key + "/";
                    return true;
                }
            }
            catch (Exception e)
            {
                Io.PrintToConsole(e.Message);
            }

            Session = new SessionData();
            return false;
        }
        // -----------------------------------------------------------------
        /// <summary>
        /// 
        /// </summary>
        // -----------------------------------------------------------------
        private static RequestBase DeserializeFromReader(JsonReader reader)
        {
            List<JsonConverter> clist = new List<JsonConverter>();
            clist.Add(new Vector3Converter());
            clist.Add(new UUIDConverter());
            clist.Add(new QuaternionConverter());

            TypeNameSerializationBinder binder = new TypeNameSerializationBinder("{0}");
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.Binder = binder;
            settings.TypeNameHandling = TypeNameHandling.Objects;
            settings.Converters = clist;

            JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
            object result = jsonSerializer.Deserialize(reader, null);
            if (result == null)
                return null;

            return ((RequestBase)result);
        }
        // -----------------------------------------------------------------
        /// <summary>
        /// 
        /// </summary>
        // -----------------------------------------------------------------
        public string SerializeToString()
        {
            List<JsonConverter> clist = new List<JsonConverter>();
            clist.Add(new Vector3Converter());
            clist.Add(new UUIDConverter());
            clist.Add(new QuaternionConverter());

            // The type name handling is pretty verbose here, but makes deserialization
            // symmetric, its enough information to figure out how to handle the structures
            TypeNameSerializationBinder binder = new TypeNameSerializationBinder("{0}, {1}");
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.Binder = binder;
            settings.TypeNameHandling = TypeNameHandling.Objects;
            settings.Converters = clist;

            return JsonConvert.SerializeObject(this, Formatting.None, settings);
        }
        // -----------------------------------------------------------------
        /// <summary>
        /// 
        /// </summary>
        // -----------------------------------------------------------------
        public byte[] SerializeToBinaryData()
        {
            List<JsonConverter> clist = new List<JsonConverter>();
            clist.Add(new Vector3Converter());
            clist.Add(new UUIDConverter());
            clist.Add(new QuaternionConverter());

            // The type name handling is pretty verbose here, but makes deserialization
            // symmetric, its enough information to figure out how to handle the structures
            TypeNameSerializationBinder binder = new TypeNameSerializationBinder("{0}, {1}");
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.Binder = binder;
            settings.TypeNameHandling = TypeNameHandling.Objects;
            settings.Converters = clist;

            JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);

            MemoryStream ms = new MemoryStream();
            BsonWriter bson = new BsonWriter(ms);

            jsonSerializer.Serialize(bson, this, null);
            return ms.ToArray();
        }
        public void SerializeUsingCustomBinder()
        {
            TypeNameSerializationBinder binder = new TypeNameSerializationBinder("Newtonsoft.Json.Tests.Serialization.{0}, Newtonsoft.Json.Tests");

            IList <object> values = new List <object>
            {
                new Customer
                {
                    Name = "Caroline Customer"
                },
                new Purchase
                {
                    ProductName = "Elbow Grease",
                    Price       = 5.99m,
                    Quantity    = 1
                }
            };

            string json = JsonConvert.SerializeObject(values, Formatting.Indented, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Binder           = binder
            });

            //[
            //  {
            //    "$type": "Customer",
            //    "Name": "Caroline Customer"
            //  },
            //  {
            //    "$type": "Purchase",
            //    "ProductName": "Elbow Grease",
            //    "Price": 5.99,
            //    "Quantity": 1
            //  }
            //]


            Assert.AreEqual(@"[
  {
    ""$type"": ""Customer"",
    ""Name"": ""Caroline Customer""
  },
  {
    ""$type"": ""Purchase"",
    ""ProductName"": ""Elbow Grease"",
    ""Price"": 5.99,
    ""Quantity"": 1
  }
]", json);

            IList <object> newValues = JsonConvert.DeserializeObject <IList <object> >(json, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Binder           = new TypeNameSerializationBinder("Newtonsoft.Json.Tests.Serialization.{0}, Newtonsoft.Json.Tests")
            });

            CustomAssert.IsInstanceOfType(typeof(Customer), newValues[0]);
            Customer customer = (Customer)newValues[0];

            Assert.AreEqual("Caroline Customer", customer.Name);

            CustomAssert.IsInstanceOfType(typeof(Purchase), newValues[1]);
            Purchase purchase = (Purchase)newValues[1];

            Assert.AreEqual("Elbow Grease", purchase.ProductName);
        }
Example #13
0
 public CollectionInterfaceConverterForModels()
 {
     Binder = new TypeNameSerializationBinder("Cartable.Models.{0}, Cartable");
 }