Draco18s

Unity Contract Resolver

May 13th, 2021
763
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. JsonSerializerSettings settings = new JsonSerializerSettings();
  2. settings.ContractResolver = new ContractResolver();
  3.  
  4. ...
  5.  
  6.     public class ContractResolver : DefaultContractResolver {
  7.             public override JsonContract ResolveContract(Type type) {
  8.                 JsonContract contract = base.ResolveContract(type);
  9.                 if(typeof(Vector2Int).IsAssignableFrom(type)) {
  10.                     contract.Converter = new Vector2IntConverter();
  11.                 }
  12.                 return contract;
  13.             }
  14.  
  15.             //don't remember what this does or if it is needed.
  16.             protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) {
  17.                 IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
  18.                
  19.                 foreach(JsonProperty prop in properties) {
  20.                     prop.DefaultValueHandling = DefaultValueHandling.Ignore;
  21.                 }
  22.  
  23.                 return properties;
  24.             }
  25.         }
  26.  
  27.         //sample Unity Vector resolver.
  28.         public class Vector2IntConverter : JsonConverter {
  29.             public override bool CanConvert(Type objectType) {
  30.                 return typeof(Vector2Int).IsAssignableFrom(objectType);
  31.             }
  32.  
  33.             public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
  34.                 JObject jObject = JObject.Load(reader);
  35.                 return new Vector2Int((int)jObject.GetValue("x"), (int)jObject.GetValue("y"));
  36.             }
  37.  
  38.             public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
  39.                 Vector2Int v = (Vector2Int)value;
  40.                 JObject o = new JObject();
  41.                 o.Add(new JProperty("x", v.x));
  42.                 o.Add(new JProperty("y", v.y));
  43.                 o.WriteTo(writer);
  44.             }
  45.  
  46.             public override bool CanRead {
  47.                 get { return true; }
  48.             }
  49.         }
RAW Paste Data