Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //JSON file
- {
- "STR": 2,
- "INT": 3,
- "DEX": 4,
- "StatsAvailable": 7
- }
- //Program.cs
- using Newtonsoft.Json;
- Player player = DataService.Load<Player>(nameof(Player));
- // DataService.Save(nameof(Player), player);
- Console.WriteLine($"TEST: {player.STR.Value}");
- string json = JsonConvert.SerializeObject(player, Formatting.Indented);
- Console.WriteLine(json);
- [Serializable]
- public class Player
- {
- public readonly ReactiveProperty<int> STR = new ReactiveProperty<int>();
- public readonly ReactiveProperty<int> INT = new ReactiveProperty<int>();
- public readonly ReactiveProperty<int> DEX = new ReactiveProperty<int>();
- public int StatsAvailable;
- public Player()
- {
- STR.Value = 0;
- INT.Value = 0;
- DEX.Value = 0;
- StatsAvailable = 10;
- }
- }
- public class ReactiveProperty<T>
- {
- public event Action<T> OnChanged;
- private T _value;
- public T Value
- {
- get => _value;
- set
- {
- _value = value;
- OnChanged?.Invoke(_value);
- }
- }
- }
- using Newtonsoft.Json;
- public static class DataService
- {
- public static void Save<T>(string key, T data)
- {
- string filePath = GetFilePath(key);
- string jsonDataString = JsonConvert.SerializeObject(data, new JsonSerializerSettings
- {
- Formatting = Formatting.Indented,
- TypeNameHandling = TypeNameHandling.Auto,
- Converters = new List<JsonConverter> { new ReactivePropertyConverter() }
- });
- // Запис у файл за допомогою StreamWriter.
- File.WriteAllText(filePath, jsonDataString);
- }
- public static T Load<T>(string key) where T : new()
- {
- string filePath = GetFilePath(key);
- if (!File.Exists(filePath))
- {
- return new T();
- }
- string json = File.ReadAllText(filePath);
- var jc = JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings
- {
- // Ті ж налаштування, що і при серіалізації
- Formatting = Formatting.Indented,
- TypeNameHandling = TypeNameHandling.Auto,
- Converters = new List<JsonConverter> { new ReactivePropertyConverter() }
- });
- return jc!;
- }
- private static string GetFilePath(string key)
- {
- return Path.Combine(Directory.GetCurrentDirectory(), key + ".json");
- }
- }
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- public class ReactivePropertyConverter : JsonConverter
- {
- public override bool CanConvert(Type objectType)
- {
- return objectType.IsGenericType &&
- objectType.GetGenericTypeDefinition() == typeof(ReactiveProperty<>) ||
- objectType.GetProperty("Value") != null;
- }
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
- {
- if (reader.TokenType == JsonToken.StartObject)
- {
- JToken token = JToken.Load(reader);
- return token.ToObject(objectType, serializer);
- }
- else if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(ReactiveProperty<>))
- {
- Type valueType = objectType.GetGenericArguments()[0];
- object value = serializer.Deserialize(reader, valueType);
- var reactiveProp = Activator.CreateInstance(objectType);
- objectType.GetProperty("Value").SetValue(reactiveProp, value);
- return reactiveProp;
- }
- throw new JsonSerializationException("Неочікуваний формат JSON для ReactiveProperty.");
- }
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
- {
- // Серіалізація
- var token = JToken.FromObject(value);
- if (token.Type == JTokenType.Object && value.GetType().IsGenericType && value.GetType().GetGenericTypeDefinition() == typeof(ReactiveProperty<>))
- {
- // Якщо це ReactiveProperty, серіалізуємо тільки Value
- var valProp = value.GetType().GetProperty("Value");
- var val = valProp.GetValue(value);
- token = JToken.FromObject(val);
- }
- token.WriteTo(writer);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement