Created
April 27, 2022 21:12
-
-
Save atcarter714/957806cfbe7456a91e93056d2b741f6c to your computer and use it in GitHub Desktop.
Easy JSON serialization for data-container classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#region Using Directives | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Newtonsoft.Json; | |
using UnityEngine; | |
#endregion | |
/// <summary> | |
/// Contract of a data object convertible to JSON data | |
/// </summary> | |
public interface IJSONObject | |
{ | |
/// <summary> | |
/// Converts the IJSONObject instance to formatted JSON string | |
/// </summary> | |
/// <returns>Object in JSON string form</returns> | |
string ToJSONString (); | |
}; | |
/// <summary> | |
/// Interface of an object convertible to/from JSON data | |
/// </summary> | |
/// <typeparam name="T">Concrete type of data</typeparam> | |
public interface IJSONObject<T>: | |
IJSONObject where T : class, IJSONObject | |
{ | |
/// <summary> | |
/// Creates copy of the object with the same field values | |
/// </summary> | |
/// <typeparam name="T">Type of IJSONObject class</typeparam> | |
/// <returns>A .NET object instance</returns> | |
T MakeCopy () ; | |
}; | |
/// <summary> | |
/// Abstract base class of JSON convertible types | |
/// which represent game data | |
/// </summary> | |
/// <typeparam name="T"> | |
/// Concrete type of an IJSONObject | |
/// </typeparam> | |
[Serializable] public abstract class JSONObjectBase<T> : | |
IJSONObject<T> where T: class, IJSONObject | |
{ | |
/// <summary> | |
/// Serializes object to JSON data string | |
/// </summary> | |
/// <returns>JSON data string</returns> | |
public virtual string ToJSONString () => | |
JsonConvert.SerializeObject ( this ); | |
/// <summary> | |
/// Creates a clone/copy with same field values | |
/// </summary> | |
/// <returns>Copy of this instance</returns> | |
public virtual T MakeCopy ( ) | |
=> (T) this.MemberwiseClone (); | |
/// <summary> | |
/// Creates an C# object from a JSON data string | |
/// </summary> | |
/// <param name="data">JSON data in string form</param> | |
/// <returns>A C# object created from JSON data</returns> | |
public static T CreateFromJSONData ( string data ) => | |
JsonConvert.DeserializeObject<T> ( data ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment