序列化和反序列化扩展IEnumerable <KeyValuePair >的类型
我在C#中使用Parse.com的API并尝试序列化扩展ParseObject的类:
[ParseClassName("Battle")] public class Battle : ParseObject { [ParseFieldName("mapName")] public string MapName { get { return GetProperty("MapName"); } set { SetProperty(value, "MapName"); } } }
因为ParseObject是
IEnumerable<KeyValuePair>
输出错误:
[ { "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或有任何想法我应该怎么做呢?
上述就是C#学习教程:序列化和反序列化扩展IEnumerable <KeyValuePair >的类型分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1005654.html