Skip to content

Instantly share code, notes, and snippets.

@izackp
Created February 14, 2015 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izackp/39e1e150b41fced0680a to your computer and use it in GitHub Desktop.
Save izackp/39e1e150b41fced0680a to your computer and use it in GitHub Desktop.
Serializer for a key as string only dictionary with Full Serializer library (used with unity). This works around the ugly produced dictionaries with key and value properties in the json. It also makes it easier for hand made json.
using FullSerializer;
using System.Collections.Generic;
[fsObject(Converter = typeof(DictionaryConverter))]
public class Dictionary<TValue> : Dictionary<string, TValue> {
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using FullSerializer;
using FullSerializer.Internal;
public class DictionaryConverter : fsConverter {
public override bool CanProcess(Type type) {
return type.Resolve().IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<>);
}
public override bool RequestCycleSupport(Type storageType) {
return false;
}
public override bool RequestInheritanceSupport(Type storageType) {
return false;
}
public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
var result = fsResult.Success;
if ((result += CheckType(data, fsDataType.Object)).Failed) {
return result;
}
Dictionary<string, fsData> serializedDic = data.AsDictionary;
Object deserializedDic = Activator.CreateInstance(storageType);
MethodInfo add = storageType.GetFlattenedMethod("Add");
Type[] typeParameters = deserializedDic.GetType().GetGenericArguments();
var valueType = typeParameters[0];
foreach(KeyValuePair<string, fsData> entry in serializedDic)
{
object deserialized = null;
var itemResult = Serializer.TryDeserialize(entry.Value, valueType, ref deserialized);
result.AddMessages(itemResult);
if (itemResult.Failed)
continue;
add.Invoke(deserializedDic, new object[] { entry.Key, deserialized });
}
instance = deserializedDic;
return result;
}
public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
var result = fsResult.Success;
serialized = fsData.CreateDictionary();
Type[] typeParameters = storageType.GetGenericArguments();
var valueType = typeParameters[0];
foreach(DictionaryEntry entry in (IDictionary)instance)
{
fsData valueData;
result.AddMessages(Serializer.TrySerialize(valueType, entry.Value, out valueData));
serialized.AsDictionary[(string)entry.Key] = valueData;
}
return fsResult.Success;
}
}
@jagt
Copy link

jagt commented Mar 8, 2015

On line 32 maybe you mean

var valueType = typeParameters[1];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment