Can’t cast objects from Dictionary after using json.net deserialization
我对反序列化字典有疑问。我无法将 Dictionary 中的对象转换为我的类型 Remiza…我正在使用 Json.net,我可以看到 Dictionary 中的对象是 JObject 而不是 Object,我不能将它们转换为我的类型。这是我的序列化/反序列化代码:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
private static Dictionary<Type, List<Object>> _ekstensje = new Dictionary<Type, List<Object>>();
public static void SerializeDictionary() file.Close(); public static void DeserializeDictionary() file.Close(); public static List<Object> GetEkstensja(Type className) |
执行:
1
2 3 4 5 6 7 |
ObjectPlus.DeserializeDictionary();
List<Object> list = ObjectPlus.GetEkstensja(typeof(Remiza)); foreach (Object o in list) { Remiza r = (Remiza) o; listaRemiz.Add(r); } |
我的问题是在投射到”Remiza”时出现异常:
1
|
An exception of type ‘System.InvalidCastException’ occurred in Osek_MAS_WPF.exe but was not handled in user code. Additional information: Unable to cast object of type ‘Newtonsoft.Json.Linq.JObject’ to type ‘Osek_MAS_WPF.Remiza’.
|
感谢您的帮助!
这应该允许您将 JObect 转换为您的 Remiza 类型。
1
2 3 4 5 6 7 |
ObjectPlus.DeserializeDictionary();
List<Object> list = ObjectPlus.GetEkstensja(typeof(Remiza)); foreach (Object o in list) { Remiza r = o.ToObject<Remiza>(); listaRemiz.Add(r); } |
我从下面链接的 stackoverflow 答案中得到了这个。如果我放的东西不起作用,请查看链接,它应该可以帮助您运行它。
https://stackoverflow.com/a/10221594/634769
为了使用 Json.NET 成功序列化和反序列化多态类型,您需要设置
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
public class ObjectPlus { // Replace with whatever file name is appropriate. My computer doesn’t have a"c://tmp" directory. static string JsonFileName { get { return Path.Combine(Path.GetTempPath(),"dictionary.json"); } } static JsonSerializerSettings JsonSettings { get { return new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto, Formatting = Formatting.Indented }; } } private static Dictionary<Type, List<Object>> _ekstensje = new Dictionary<Type, List<Object>>(); public static void SerializeDictionary() using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) public static void DeserializeDictionary() public static List<Object> GetEkstensja(Type className) public static void AddEkstensja< T >(T obj) internal static string ShowJsonContents() |
您现在应该能够在字典包含
的实例时对其进行序列化和反序列化
这适用于序列化为对象或集合的类型。但是,如果您的字典包含序列化为 JSON 原语的类型 – 例如
(顺便说一句,您的
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/269528.html