public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var serializationData = SerializationData.GetSerializationData(writer); if (!serializationData.HasProcessedDocumentRoot) { //treat this value as a document root DocumentRootConverter.ResolveAsRootData(writer, value, serializer); return; } var contractResolver = serializer.ContractResolver; var enumerable = value as IEnumerable <object> ?? Enumerable.Empty <object>(); writer.WriteStartArray(); foreach (var valueElement in enumerable) { if (valueElement == null || !(contractResolver.ResolveContract(valueElement.GetType()) is ResourceObjectContract)) { throw new JsonApiFormatException(writer.Path, $"Expected to find to find resource objects within lists, but found '{valueElement}'", "Resource identifier objects MUST contain 'id' members"); } serializer.Serialize(writer, valueElement); } writer.WriteEndArray(); }
//public static void Test(object o) //{ // try // { // string a = UON.ToUON(o); // Debug.Log(a); // object c = UON.FromUON(a); // string b = UON.ToUON(c); // Debug.Log(b); // Debug.Log(b.Equals(a) == true ? "<color=green>VALID</color>" : "<color=red>FAILED</color>"); // } // catch (Exception ex) // { // Debug.LogException(ex); // } //} /// <summary>Converts <paramref name="instance"/> into UON.</summary> /// <param name="instance">Can be of any types, Unity Object, array, list, struct or class.</param> /// <returns>A UON of the given <paramref name="instance"/>.</returns> public static string ToUON(object instance) { if (instance == null) { return("[]"); } SerializationData data = new SerializationData() { workingType = instance.GetType() }; data.registeredTypes.Add(instance.GetType()); for (int i = 0; i < UON.types.Length; i++) { if (UON.types[i] is UnityObjectUON) { continue; } if (UON.types[i].Can(data.workingType) == true) { return(data.Generate(UON.types[i].Serialize(data, instance))); } } throw new UnhandledTypeException("Object of type " + instance.GetType().FullName + " not handled."); }
public bool LoadFile(string file) { try { if (File.Exists(file)) { SerializationData data = new SerializationData(); using (StreamReader reader = new StreamReader(file, Encoding.UTF8)) { XmlSerializer serializer = new XmlSerializer(typeof(SerializationData)); data = (SerializationData)serializer.Deserialize(reader); reader.Close(); } comparisonGraph1.EquipSlot = CharacterSlot.AutoSelect; comparisonGraph1.Character = FormMain.Instance.Character; SetCustomSubpoints(data.CustomSubpoints); _itemCalculations = new Dictionary <string, ComparisonCalculationUpgrades[]>(); for (int i = 0; i < data.Keys.Count; i++) { _itemCalculations[data.Keys[i]] = data.ItemCalculations[i]; } slotToolStripMenuItem_Click(allToolStripMenuItem, null); return(true); } } catch { MessageBox.Show("The chosen file is not a Rawr Upgrade List.", "Unable to Load Upgrade List", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return(false); }
private void SaveFile(string file) { SerializationData data = new SerializationData(); data.CustomSubpoints = customSubpoints; data.Keys = new List <string>(); data.ItemCalculations = new List <ComparisonCalculationUpgrades[]>(); foreach (KeyValuePair <string, ComparisonCalculationUpgrades[]> kvp in _itemCalculations) { data.Keys.Add(kvp.Key); data.ItemCalculations.Add(kvp.Value); } try { using (StreamWriter writer = new StreamWriter(file, false, Encoding.UTF8)) { XmlSerializer serializer = new XmlSerializer(typeof(SerializationData)); serializer.Serialize(writer, data); writer.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static SerializationData Serialize(object obj) { if (obj == null) { throw new Exception("序列化目标对象不能为null"); } SerializationData elem = new SerializationData { Type = obj.GetType().FullName }; TypeIdentifyAttribute typeIdentify = obj.GetType().GetCustomAttribute <TypeIdentifyAttribute>(); if (typeIdentify != null) { elem.TypeGUID = typeIdentify.GUID; } if (string.IsNullOrWhiteSpace(elem.TypeGUID)) { Debug.LogErrorFormat("序列化类型 {0} 缺少TypeIdentify 属性,类重名将会丢失数据", elem.Type); } #if UNITY_EDITOR elem.JsonDatas = UnityEditor.EditorJsonUtility.ToJson(obj); #else elem.JsonDatas = UnityEngine.JsonUtility.ToJson(obj); #endif return(elem); }
// Deserialize component defined in the ComponentNode public Component Deserialize(XmlNode ComponentNode) { // Find type from component nodes name Assembly a = Assembly.Load(DependencyMap[ComponentNode.LocalName]); Type t = a.GetType(ComponentNode.LocalName); // Create an instance of the type and a SerializationData object Component component = (Component)Activator.CreateInstance(t); SerializationData data = new SerializationData(this, null); // For each field defined, get its value and add the field to SerializationData foreach (XmlNode child in ComponentNode.ChildNodes) { // Make name and object values, and get // the name from the 0 attribute. string name = child.Attributes[0].Value; object value = null; // If the field node contains text only, it's a value type // and we can set the object directly if (child.ChildNodes[0].NodeType == XmlNodeType.Text) value = parse(child); // Otherwise we need to recreate a more complex object from the data else if (child.ChildNodes[0].NodeType == XmlNodeType.Element) value = parseTree(child.FirstChild); // Save the field to the SerializationData data.AddData(name, value); } // Tell the component to load from the data component.RecieveSerializationData(data); return component; }
private object ReadJsonAsResourceObject(ForkableJsonReader reader, Type objectType, JsonSerializer serializer) { // if the value has been explicitly set to null then the value of the element is simply null if (reader.TokenType == JsonToken.Null) { return(null); } var serializationData = SerializationData.GetSerializationData(reader); var jsonApiContractResolver = (JsonApiContractResolver)serializer.ContractResolver; var reference = ReaderUtil.ReadAheadToIdentifyObject(reader); if (serializationData.Included.TryGetValue(reference, out object resourceObject)) { if (resourceObject is JObject resoruceObjectJObject) { // sometimes the value in the reference resolver is a JObject. This occurs when we // did not know what type it should be when we first read it (i.e. included was processed // before the item). In these cases we now know what type it should be so will read it // as such var resourceObjectReader = new ForkableJsonReader(resoruceObjectJObject.CreateReader(), reader.SerializationDataToken); resourceObjectReader.Read(); //JObject readers begin at Not Started resourceObject = jsonApiContractResolver.ResourceObjectConverter.ReadJson( resourceObjectReader, objectType, null, serializer); } //push the reader to the end, we dont need anything else out of the reference ReaderUtil.ReadUntilEnd(reader, reader.Path); } else { var contract = (JsonObjectContract)jsonApiContractResolver.ResolveContract(objectType); resourceObject = ReaderUtil.CreateObject(serializationData, objectType, reference.Type, serializer); // for placeholders we will just read the top level properties // it is unlikely to have attributes/relationships present foreach (var propName in ReaderUtil.IterateProperties(reader)) { var successfullyPopulateProperty = ReaderUtil.TryPopulateProperty( serializer, resourceObject, contract.Properties.GetClosestMatchProperty(propName), reader); } serializationData.Included[reference] = resourceObject; } if (!TypeInfoShim.IsInstanceOf(objectType.GetTypeInfo(), resourceObject)) { throw new JsonSerializationException($"Unable to assign object '{resourceObject}' to type '{objectType}' at path {reader.FullPath}"); } return(resourceObject); }
internal static bool TryResolveAsRootError(JsonReader reader, Type objectType, JsonSerializer serializer, out IEnumerable <IError> obj) { var serializationData = SerializationData.GetSerializationData(reader); //if we already have a root object then we dont need to resolve the root object if (serializationData.HasProcessedDocumentRoot) { obj = null; return(false); } //determine the error class type. The type passed in could be an array or an object //so we need to determine the error type for both Type errorElementType; if (!ListUtil.IsList(objectType, out errorElementType)) { errorElementType = objectType; } //we do not have a root object, so this is probably the entry point, so we will resolve //a document root and return the data object var documentRootType = typeof(MinimalDocumentRoot <,>).MakeGenericType(typeof(object), errorElementType); var objContract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(documentRootType); var dataProp = objContract.Properties.GetClosestMatchProperty("errors"); var root = serializer.Deserialize(reader, documentRootType); obj = (IEnumerable <IError>)dataProp.ValueProvider.GetValue(root); return(true); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var serializationData = SerializationData.GetSerializationData(reader); var forkableReader = reader as ForkableJsonReader ?? new ForkableJsonReader(reader); var jsonApiContractResolver = (JsonApiContractResolver)serializer.ContractResolver; var contract = jsonApiContractResolver.ResolveContract(objectType); switch (contract) { case ResourceObjectContract roc: return(ReadJsonAsResourceObject(forkableReader, objectType, serializer)); case ResourceIdentifierContract ric: return(ReadJsonAsExplicitResourceIdentifier(forkableReader, objectType, serializer)); case JsonArrayContract jac when forkableReader.TokenType == JsonToken.StartArray: var list = new List <object>(); foreach (var item in ReaderUtil.IterateList(forkableReader)) { list.Add(ReadJson(forkableReader, jac.CollectionItemType, null, serializer)); } return(ListUtil.CreateList(objectType, list)); default: return(serializer.Deserialize(reader, objectType)); throw new JsonApiFormatException( forkableReader.FullPath, $"Expected to find a resource identifier or resource object, but found '{objectType}'", "Resource indentifier objects MUST contain 'id' members"); } }
public static object CreateObject(SerializationData serializationData, Type objectType, string jsonApiType, JsonSerializer serializer) { // Hack: To keep backward compatability we are not sure what resouceObjectConverter to use // we need to check if either one was defined as a serializer, or if one was defined as // furher up the stack (i.e. a member converter) for (var i = 0; i < serializer.Converters.Count; i++) { var converter = serializer.Converters[i]; if (converter is ResourceObjectConverter roc && converter.CanRead && converter.CanConvert(objectType)) { return(roc.CreateObjectInternal(objectType, jsonApiType, serializer)); } } foreach (var converter in serializationData.ConverterStack) { if (converter is ResourceObjectConverter roc) { return(roc.CreateObjectInternal(objectType, jsonApiType, serializer)); } } return(serializer.ContractResolver.ResolveContract(objectType).DefaultCreator()); }
//... private void LoadPrefs() { if (data == null) { var json = EditorPrefs.GetString(PREFERENCES_KEY); if (!string.IsNullOrEmpty(json)) { data = JSONSerializer.Deserialize <SerializationData>(json); } if (data == null) { data = new SerializationData(); } filterFavorites = data.filterFavorites; if (currentKeyType != null) { data.allFavorites.TryGetValue(currentKeyType.Name, out favorites); } if (favorites == null) { favorites = new List <string>(); } } }
private void WriteExplicitIdentifierJson(JsonWriter writer, object value, JsonSerializer serializer) { var serializationData = SerializationData.GetSerializationData(writer); var valueType = value.GetType(); var resourceIdentifierContract = (ResourceIdentifierContract)serializer.ContractResolver.ResolveContract(valueType); var resourceObject = resourceIdentifierContract.ResourceObjectProperty.ValueProvider.GetValue(value); if (resourceObject == null) { writer.WriteNull(); return; } var resourceObjectType = resourceObject.GetType(); var resourceObjectContract = (ResourceObjectContract)serializer.ContractResolver.ResolveContract(resourceObjectType); writer.WriteStartObject(); //A "resource identifier object" MUST contain type and id members. //serialize id WriterUtil.ShouldWriteStringProperty(writer, resourceObject, resourceObjectContract.IdProperty, serializer, out string id); writer.WritePropertyName(PropertyNames.Id); writer.WriteValue(id); //serialize type. Will always out put a type WriterUtil.ShouldWriteStringProperty(writer, resourceObject, resourceObjectContract.TypeProperty, serializer, out string type); type = type ?? WriterUtil.CalculateDefaultJsonApiType(resourceObject, serializationData, serializer); writer.WritePropertyName(PropertyNames.Type); writer.WriteValue(type); for (var i = 0; i < resourceIdentifierContract.Properties.Count; i++) { var resourceIdentifierProp = resourceIdentifierContract.Properties[i]; if (resourceIdentifierProp == resourceIdentifierContract.ResourceObjectProperty) { continue; } switch (resourceIdentifierProp.PropertyName) { case PropertyNames.Id: case PropertyNames.Type: break; default: if (WriterUtil.ShouldWriteProperty(value, resourceIdentifierProp, serializer, out object propValue)) { writer.WritePropertyName(resourceIdentifierProp.PropertyName); serializer.Serialize(writer, propValue); } break; } } writer.WriteEndObject(); var reference = new ResourceObjectReference(id, type); serializationData.Included[reference] = resourceObject; }
public UpgradesComparison(TextReader reader) { InitializeComponent(); MainPage.Instance.UpgradeListOpen = true; Graph.Mode = ComparisonGraph.DisplayMode.Overall; Graph.Character = MainPage.Instance.Character; try { XmlSerializer serializer = new XmlSerializer(typeof(SerializationData)); SerializationData data = (SerializationData)serializer.Deserialize(reader); SetCustomSubpoints(data.CustomSubpoints); itemCalculations = new Dictionary <string, ComparisonCalculationUpgrades[]>(); for (int i = 0; i < data.Keys.Count; i++) { itemCalculations[data.Keys[i]] = data.ItemCalculations[i]; } SlotCombo.SelectedIndex = 0; } catch (Exception /*e*/) { Close(); MessageBox.Show("The chosen file is not a Rawr Upgrade List.", "Unable to Load Upgrade List", MessageBoxButton.OK); } finally { reader.Dispose(); } }
public static object Deserialize(SerializationData e) { Type type = null; if (string.IsNullOrEmpty(e.TypeGUID) || !TypeGUIDs.TryGetValue(e.TypeGUID, out type)) { if (!string.IsNullOrEmpty(e.Type)) { type = Type.GetType(e.Type); } } if (type == null) { Debug.LogErrorFormat("反序列化失败,缺少类型 {0}, json数据:\n {1}", e.Type, e.JsonDatas); return(null); } var obj = Activator.CreateInstance(type); #if UNITY_EDITOR UnityEditor.EditorJsonUtility.FromJsonOverwrite(e.JsonDatas, obj); #else UnityEngine.JsonUtility.FromJsonOverwrite(e.JsonDatas, obj); #endif return(obj); }
public void OnBeforeSerialize() { if (nodeData != null) { serializeData = TypeSerializerHelper.Serialize(nodeData); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var forkableReader = reader as ForkableJsonReader ?? new ForkableJsonReader(reader); var reference = ReaderUtil.ReadAheadToIdentifyObject(forkableReader); var serializationData = SerializationData.GetSerializationData(forkableReader); if (!serializationData.Included.TryGetValue(reference, out var existingObject)) { //we dont know what type this object should be so we will just save it as a JObject var unknownObject = serializer.Deserialize <JObject>(forkableReader); serializationData.Included.Add(reference, unknownObject); return(unknownObject); } else if (existingObject is JObject) { //we already have a resolved object that we dont know what the type is, we will keep the first one return(existingObject); } else { //We have an existing object, its likely our included data has more detail than what //is currently on the object so we will pass the reader so it can be deserialized again var type = existingObject.GetType(); var existingObjectContract = serializer.ContractResolver.ResolveContract(type); return(existingObjectContract.Converter.ReadJson(reader, type, existingObject, serializer)); } }
internal static bool TryResolveAsRootError(JsonWriter writer, object value, JsonSerializer serializer) { var serializationData = SerializationData.GetSerializationData(writer); //if we already have a root object then we dont need to resolve the root object if (serializationData.HasProcessedDocumentRoot) { return(false); } //coerce single element into a list if (value is IError) { value = new List <IError>() { (IError)value } } ; //we do not have a root object, so this is probably the entry point, so we will resolve //it as a document root var documentRootType = typeof(MinimalDocumentRoot <,>).MakeGenericType(typeof(object), typeof(IError)); var objContract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(documentRootType); var rootObj = objContract.DefaultCreator(); //set the data property to be our current object var dataProp = objContract.Properties.GetClosestMatchProperty("errors"); dataProp.ValueProvider.SetValue(rootObj, value); serializer.Serialize(writer, rootObj); return(true); }
public void Serialize() { #if DBG Log("Saving " + GetType().Name); #endif SerializationData.Clear(); Serializer.SerializeTargetIntoData(this, SerializationData); }
public void ApplyLoadedData() { SerializationData data = SerializationHelper.GetData(SerializationKey); Items = (ObservableCollection <T>)data.Data["Items"]; Capacity = (int)data.Data["Capacity"]; Position = (int)data.Data["Position"]; }
void IManager.LoadSerializationData(SerializationData data) { this.Layers = (MiyagiCollection <Layer>)data["Layers"]; foreach (var layer in this.Layers) { this.AddLayer(layer); } }
public static SerializationData Create() { var s = new SerializationData(); s.itemNames = ItemNames.ToArray(); s.actors = Actors.ToArray(); return(s); }
private void WriteResourceObjectJson(JsonWriter writer, object resourceObject, JsonSerializer serializer) { if (resourceObject == null) { writer.WriteNull(); return; } var serializationData = SerializationData.GetSerializationData(writer); var resourceObjectType = resourceObject.GetType(); var resourceObjectContract = (ResourceObjectContract)serializer.ContractResolver.ResolveContract(resourceObjectType); writer.WriteStartObject(); //A "resource identifier object" MUST contain type and id members. //serialize id WriterUtil.ShouldWriteProperty(resourceObject, resourceObjectContract.IdProperty, serializer, out string id); writer.WritePropertyName(PropertyNames.Id); writer.WriteValue(id); //serialize type. Will always out put a type WriterUtil.ShouldWriteProperty(resourceObject, resourceObjectContract.TypeProperty, serializer, out string type); type = type ?? WriterUtil.CalculateDefaultJsonApiType(resourceObject, serializationData, serializer); writer.WritePropertyName(PropertyNames.Type); writer.WriteValue(type); //we will only write the object to included if there are properties that have have data //that we cant include within the reference var willWriteObjectToIncluded = WriterUtil.ShouldWriteProperty(resourceObject, resourceObjectContract.LinksProperty, serializer, out object _); for (var i = 0; i < resourceObjectContract.Attributes.Length && !willWriteObjectToIncluded; i++) { willWriteObjectToIncluded = WriterUtil.ShouldWriteProperty(resourceObject, resourceObjectContract.Attributes[i], serializer, out object _); } for (var i = 0; i < resourceObjectContract.Relationships.Length && !willWriteObjectToIncluded; i++) { willWriteObjectToIncluded = WriterUtil.ShouldWriteProperty(resourceObject, resourceObjectContract.Relationships[i], serializer, out object _); } // typically we would just write the meta in the included. But if we are not going to // have something in included we will write the meta inline here if (!willWriteObjectToIncluded && WriterUtil.ShouldWriteProperty(resourceObject, resourceObjectContract.MetaProperty, serializer, out object metaVal)) { writer.WritePropertyName(PropertyNames.Meta); serializer.Serialize(writer, metaVal); } writer.WriteEndObject(); if (willWriteObjectToIncluded) { var reference = new ResourceObjectReference(id, type); serializationData.Included[reference] = resourceObject; } }
/// <inheritdoc/> public void AddValue(string key, object value, Type type = null) { if (type == null) { type = value == null ? typeof(object) : value.GetType(); } data[key] = new SerializationData(value, type); }
void IManager.LoadSerializationData(SerializationData data) { this.Cursor = (Cursor)data["Cursor"]; this.GUIs = (MiyagiCollection <GUI>)data["GUIs"]; foreach (var gui in this.guis) { this.AddGUI(gui); } }
/// <summary> /// Serializes all objects as one object graph and writes their serialized bytes /// into the given List of bytes. The objects are serialized one after another as /// returned by the Lists iterator. /// For more details see the documentation of Serialize(SerializationData, object). /// </summary> /// <param name="obj">The object to serialize.</param> public static void Serialize(List <byte> bytes, List <object> objects) { SerializationData data = new SerializationData(); data.bytes = bytes; foreach (var obj in objects) { Serialize(data, obj); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var serializationData = SerializationData.GetSerializationData(reader); reader = new ForkableJsonReader(reader); var contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(objectType); var rootObject = contract.DefaultCreator(); serializationData.HasProcessedDocumentRoot = true; var includedConverter = new IncludedConverter(); foreach (var propName in ReaderUtil.IterateProperties(reader)) { switch (propName) { case PropertyNames.Data: var documentRootInterfaceType = TypeInfoShim.GetInterfaces(objectType.GetTypeInfo()) .Select(x => x.GetTypeInfo()) .FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IDocumentRoot <>)); var dataType = documentRootInterfaceType.GenericTypeArguments[0]; var dataObj = serializer.Deserialize(reader, dataType); contract.Properties.GetClosestMatchProperty(PropertyNames.Data).ValueProvider.SetValue(rootObject, dataObj); break; case PropertyNames.Included: //if our object has an included property we will do our best to populate it var property = contract.Properties.GetClosestMatchProperty(propName); if (ReaderUtil.CanPopulateProperty(property)) { ReaderUtil.TryPopulateProperty(serializer, rootObject, contract.Properties.GetClosestMatchProperty(propName), ((ForkableJsonReader)reader).Fork()); } //still need to read our values so they are updated foreach (var obj in ReaderUtil.IterateList(reader)) { var includedObject = includedConverter.ReadJson(reader, typeof(object), null, serializer); } break; default: ReaderUtil.TryPopulateProperty(serializer, rootObject, contract.Properties.GetClosestMatchProperty(propName), reader); break; } } return(rootObject); }
/// <summary> /// Takes an object, serializes it and writes its byte data into the given data object. /// How the byte data looks like depends on the object given: /// if obj is null: /// a single byte equal to ChunkType.NULL /// if the obj was already written to the serialization data before: /// a single byte equal to ChunkType.ID_REF /// 2 bytes containing the objects ID. The ID is read from the objToID map in data /// if the type of the obj is not known: /// a single byte equal to ChunkType.ID_REF /// 3 bytes equal to UNKNOWN_TYPE_ID /// if the type of the obj is a primitive type: /// a single byte equal to ChunkType.PRIMITIVE /// 3 bytes with the type-ID of the primitive /// the serializer for the primitives type will be used to write all following bytes /// if the type of the obj is a known non-primitive type: /// a single byte equal to ChunkType.NEW_REF /// 3 bytes with the type-ID of the object /// the ref-ID of the object will not be written. It is determined /// deterministically from the order of writes / reads. /// the serializer for the objects type will be used to write all following bytes /// /// Attempting to write an object for which no serializer is known will result in an /// error being written to the internal error buffer. /// For more information on the error handling process refer to the documentation of /// GetErrorBuffer(). /// </summary> /// <param name="data">The serialized data used during this serialization process.</param> /// <param name="obj">The object to serialize.</param> public static void Serialize(SerializationData data, object obj) { if (obj == null) { // only write a single byte data.WriteChunkType(ChunkType.NULL); return; } short objID; bool hasID = data.objToID.TryGetValue(obj, out objID); // whether or not the same object was written before to the same data instance if (hasID) { // only write 3 bytes data.WriteChunkType(ChunkType.ID_REF); data.WriteInt2B(objID); return; } Type type = obj.GetType(); Serializer ser; bool isKnownType = typeMap.TryGetValue(type, out ser); // whether or not a known serializer exists for the given object type if (!isKnownType) { // only write 4 bytes data.WriteChunkType(ChunkType.NEW_REF); data.WriteInt3B(UNKNOWN_TYPE_ID); errBuffer.Add(new ErrorSerializeUnknownType(obj)); return; } // whether the data is a primitive (int, float, double, boolean, etc) if (ser.IsPrimitive()) { // primitives write at least 4 bytes, this is the first data.WriteChunkType(ChunkType.PRIMITIVE); } else { // this will register this object as being written to the given data // for the first time. If written to this data again in the future the // object will be serialized with less space requirements. data.RegisterObject(obj); // non-primitives write at least 4 bytes, this is the first data.WriteChunkType(ChunkType.NEW_REF); } // writes the 3 byte type-ID of the object as returned by GetTypeID(object) data.WriteInt3B(ser.id); // delegates further serialization to the serializer registered for the objects type ser.WriteBytes(data, obj); }
public override void WriteBytes(SerializationData data, System.Object obj) { string str = (string)obj; byte[] strBytes = utf8.GetBytes(str); data.WriteInt4B(strBytes.Length); for (int i = 0; i < strBytes.Length; i++) { data.bytes.Add(strBytes[i]); } }
/// <summary> /// Options data being saved. /// </summary> /// <param name="a_serializationData"></param> private void SaveOptionsData(SerializationData a_serializationData) { // Audio volume multipliers. a_serializationData.m_optionsData.m_fMasterVolume = AudioManager.m_audioManager.MasterVolume; a_serializationData.m_optionsData.m_fMusicVolume = AudioManager.m_audioManager.MusicVolume; a_serializationData.m_optionsData.m_fBulletVolume = AudioManager.m_audioManager.BulletVolume; a_serializationData.m_optionsData.m_fEffectsVolume = AudioManager.m_audioManager.EffectsVolume; a_serializationData.m_optionsData.m_fMenuButtonVolume = AudioManager.m_audioManager.MenuVolume; // Other misc options. a_serializationData.m_optionsData.m_bForceHideCursor = GameManager.m_gameManager.ForceHideCursor; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { //we may be starting the deserialization here, if thats the case we need to resolve this object as the root object obj; if (DocumentRootConverter.TryResolveAsRootData(reader, objectType, serializer, out obj)) { return(obj); } //read into the 'Data' element return(ReaderUtil.ReadInto( reader as ForkableJsonReader ?? new ForkableJsonReader(reader), DataReadPathRegex, dataReader => { //if the value has been explicitly set to null then the value of the element is simply null if (dataReader.TokenType == JsonToken.Null) { return null; } JsonObjectContract contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(objectType); var serializationData = SerializationData.GetSerializationData(dataReader); //if we arent given an existing value check the references to see if we have one in there //if we dont have one there then create a new object to populate if (existingValue == null) { var reference = ReaderUtil.ReadAheadToIdentifyObject(dataReader); if (!serializationData.Included.TryGetValue(reference, out existingValue)) { existingValue = contract.DefaultCreator(); serializationData.Included.Add(reference, existingValue); } if (existingValue is JObject) { //sometimes the value in the reference resolver is a JObject. This occurs when we //did not know what type it should be when we first read it (i.e. included was processed //before the item). In these cases we will create a new object and read data from the JObject dataReader = new ForkableJsonReader(((JObject)existingValue).CreateReader(), dataReader.SerializationDataToken); dataReader.Read(); //JObject readers begin at Not Started existingValue = contract.DefaultCreator(); serializationData.Included[reference] = existingValue; } } PopulateProperties(serializer, existingValue, dataReader, contract); return existingValue; })); }
public override void WriteBytes(SerializationData data, object obj) { FieldInfo[] props = obj.GetType().GetFields( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); foreach (var info in props) { object val = info.GetValue(obj); SerializationCtrl.Serialize(data, val); } }
// Serialize the SerializationData to file public void Serialize(XmlWriter Writer, SerializationData Input) { foreach (KeyValuePair<string, object> pair in Input.Data) { Writer.WriteStartElement("Field"); Writer.WriteAttributeString("Name", pair.Key); // We won't have an instance name here because // it is already in the Name attribute SerializeObject(Writer, pair.Value, null); Writer.WriteEndElement(); } }
public CollisionEvent(SerializationData initData, Func<int, Gob> gobFinder) : this() { var gob1 = gobFinder(initData.Gob1ID); var gob2 = gobFinder(initData.Gob2ID); if (gob1 != null && gob2 != null) { var area1 = gob1.GetCollisionArea(initData.Area1ID); var area2 = gob2.GetCollisionArea(initData.Area2ID); if (area1 == null || area2 == null) throw new ArgumentNullException("area1, area2", string.Format( "area1 is {0}, area2 is {1}, area1ID={2}, area2ID={3}, count1={4}, count2={5}", area1 == null ? "null" : "not null", area2 == null ? "null" : "not null", initData.Area1ID, initData.Area2ID, gob1.CollisionAreas.Count(), gob2.CollisionAreas.Count())); SetCollisionAreas(area1, area2); } SetCollisionSound(initData.CollisionSound); }
public void Serialize() { try { XmlSerializer xmlSerializer = new XmlSerializer(typeof(SerializationData)); StreamWriter streamWriter = new StreamWriter(SERIALIZATION_NAME); SerializationData szData = new SerializationData(); szData.Country = Model.Country; szData.CityType = Model.CityType; szData.City = Model.City; szData.IsShowGoolgeMap = IsGoogleMapActive; xmlSerializer.Serialize(streamWriter, szData); streamWriter.Close(); } catch { } }
// Overridable function to allow components to load data during deserialization public virtual void LoadFromSerializationData(SerializationData Data) { }
private void SaveButton_Clicked(object sender, RoutedEventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Rawr Upgrade List Files|*.xml"; sfd.DefaultExt = "*.xml"; if (sfd.ShowDialog().GetValueOrDefault()) { SerializationData data = new SerializationData(); data.CustomSubpoints = customSubpoints; data.Keys = new List<string>(itemCalculations.Keys); data.ItemCalculations = new List<ComparisonCalculationUpgrades[]>(itemCalculations.Values); XmlSerializer serializer = new XmlSerializer(typeof(SerializationData)); using (Stream fileStream = sfd.OpenFile()) serializer.Serialize(fileStream, data); } }
public void RecieveSerializationData(SerializationData Data) { // Set the basic Component values this.DrawOrder = Data.GetData<int>("Component.DrawOrder"); this.Visible = Data.GetData<bool>("Component.Visible"); this.Name = Data.GetData<string>("Component.Name"); // Get the ServiceData from the data ServiceData sd = Data.GetData<ServiceData>("Component.ServiceData"); // If the conponent was a service if (sd.IsService) { // Get the type back from the serializer Type t = Data.GetTypeFromDependency(sd.Type); // Add the service to the Engine Engine.Services.AddService(t, this); } // Set the owner GameScreen string parent = Data.GetData<string>("Component.ParentScreen"); this.Parent = Engine.GameScreens[parent]; // Call the overridable function that allow components to load from data LoadFromSerializationData(Data); }
// Overridable function to allow components to save data during serialization public virtual void SaveSerializationData(SerializationData Data) { }
// Returns a SerializationData a Serializer can use to save the state // of the object to an Xml file public SerializationData GetSerializationData(Serializer Serializer, XmlWriter Writer) { // Create a new SerializationData SerializationData data = new SerializationData(Serializer, Writer); // Add the basic Component values data.AddData("Component.DrawOrder", DrawOrder); data.AddData("Component.ParentScreen", Parent.Name); data.AddData("Component.Visible", Visible); data.AddData("Component.Name", this.Name); // Tell serializer that it will need to know the type of component data.AddDependency(this.GetType()); // Construct a ServiceData ServiceData sd = new ServiceData(); // If this object is a service, find out what the provider type is // (the type used to look up the services) Type serviceType; if (Engine.Services.IsService(this, out serviceType)) { // Tell serializer about provider type data.AddDependency(serviceType); // Set data to ServiceData sd.IsService = true; sd.Type = serviceType.FullName; } // Add the ServiceData to the SerializationData data.AddData("Component.ServiceData", sd); // Call the overridable function that allows components to provide data SaveSerializationData(data); return data; }