序列化和反序列化扩展IEnumerable的类型<keyvaluepair <string,object =“”>&gt; </keyvaluepair <string,>

时间:2014-10-17 06:16:10

标签: c# json parse-platform json.net

我正在使用C#中的Parse.com API并尝试序列化扩展ParseObject的类:

[ParseClassName("Battle")]
public class Battle : ParseObject
{
    [ParseFieldName("mapName")]
    public string MapName
    {
        get { return GetProperty<string>("MapName"); }
        set { SetProperty<string>(value, "MapName"); }
    }
}

因为ParseObject是

IEnumerable<KeyValuePair<string, object>>

输出错误:

[ { "Key": "mapName", "Value": "Worlds Collide" } ]

应该看起来像:

{ MapName: "Worlds Collide" }

我曾尝试编写一个自定义的JsonConverter来处理它,但我不能在我的生活中让它正确地反序列化。

public class ParseObjectJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        var can = objectType.IsSubclassOf(typeof(ParseObject));
        return can;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load JObject from stream
        var jObject = JObject.Load(reader);

        var target = Activator.CreateInstance(objectType);

        var properties = objectType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
            .Where(prop => prop.GetSetMethod() != null).ToList();

        foreach (var p in jObject.Properties())
        {
            var targetProp = properties.FirstOrDefault(prop => prop.Name == p.Name);
            if(targetProp==null) continue;               

            targetProp.SetValue(target,  p.Value, null);
        }

        return target;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var properties = value.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
            .Where(prop => prop.GetSetMethod() != null).Where(prop => prop.GetValue(value, null) != null).ToList();

        writer.WriteStartObject();

        foreach(var prop in properties)
        {
            writer.WritePropertyName(prop.Name);
            serializer.Serialize(writer, prop.GetValue(value, null));
        }

        writer.WriteEndObject();
    }    
}

有没有人尝试过序列化ParseObject,或者有任何想法我应该怎么做呢?

0 个答案:

没有答案