c# – 使用IDictionary>的自定义解析程序进行反序列化问题
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 使用IDictionary>的自定义解析程序进行反序列化问题,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4059字,纯文字阅读大概需要6分钟。
内容图文
![c# – 使用IDictionary>的自定义解析程序进行反序列化问题](/upload/InfoBanner/zyjiaocheng/787/177d2323f06b49a9b181fa4f1a486d51.jpg)
问题:
我有一个包含IDictionary< MyCustomClass,List< string>>的Foo类.我正在使用自定义的ContractResolver,如this answer所示,这样我的字典将序列化为包含“Key”和“Value”属性的对象数组.那部分工作正常.但是,当我尝试使用相同的解析器将JSON反序列化为Foo时,我收到错误,如下所示.
错误:
Run-time exception (line 46): Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
‘System.Collections.Generic.IDictionary2[mycustomclass,System.Collections.Generic.List
1[System.String]]’
because the type requires a JSON object (e.g.{"name":"value"}
) to
deserialize correctly.To fix this error either change the JSON to a JSON object (e.g.
{"name":"value"}
) or change the deserialized type to an array or a
type that implements a collection interface (e.g. ICollection, IList)
like List that can be deserialized from a JSON array.
JsonArrayAttribute can also be added to the type to force it to
deserialize from a JSON array.Path ‘Dict2’, line 12, position 13.
Dotnetfiddle:
https://dotnetfiddle.net/BKaKab
我的代码:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class mycustomclass
{
public string name {get;set;}
public List<string> Productlist {get;set;}
public List<string> SelectedItems{get;set;}
}
public class Program
{
public static void Main()
{
mycustomclass omycustomclass = new mycustomclass{name = "Test",Productlist = new string[]{"Product1","Product2","Product3"}.ToList(), SelectedItems = new string[]{"Item1","Item2","Item3"}.ToList()};
mycustomclass omycustomclass2 = new mycustomclass{name = "Test",Productlist = new string[]{"Product4","Product5","Product6"}.ToList(), SelectedItems = new string[]{"Item4","Item5","Item6"}.ToList()};
Foo foo = new Foo();
foo.Dict = new Dictionary<string, string>();
foo.Dict.Add("Gee", "Whiz");
foo.Dict.Add("Fizz", "Bang");
Dictionary<mycustomclass, List<string>> custom = new Dictionary<mycustomclass, List<string>>();
custom.Add(omycustomclass, new string[]{"l1","l2","l3"}.ToList());
custom.Add(omycustomclass2, new string[]{"l4","l5","l6"}.ToList());
foo.Dict2 = custom;
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new DictionaryAsArrayResolver();
// serialize
string json = JsonConvert.SerializeObject(foo, settings);
Console.WriteLine(json);
Console.WriteLine();
// deserialize
foo = JsonConvert.DeserializeObject<Foo>(json, settings);
foreach (var kvp in foo.Dict)
{
Console.WriteLine(kvp.Key + ": " + kvp.Value);
}
}
class Foo
{
public Dictionary<string, string> Dict { get; set; }
public IDictionary<mycustomclass, List<string>> Dict2 { get; set; }
}
}
class DictionaryAsArrayResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
if (objectType.GetInterfaces().Any(i => i == typeof(IDictionary) ||
(i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>))))
{
return base.CreateArrayContract(objectType);
}
return base.CreateContract(objectType);
}
}
JSON:
{
"Dict": [
{
"Key": "Gee",
"Value": "Whiz"
},
{
"Key": "Fizz",
"Value": "Bang"
}
],
"Dict2": [
{
"Key": {
"name": "Test",
"Productlist": [
"Product1",
"Product2",
"Product3"
],
"SelectedItems": [
"Item1",
"Item2",
"Item3"
]
},
"Value": [
"l1",
"l2",
"l3"
]
},
{
"Key": {
"name": "Test",
"Productlist": [
"Product1",
"Product2",
"Product3"
],
"SelectedItems": [
"Item1",
"Item2",
"Item3"
]
},
"Value": [
"l1",
"l2",
"l3"
]
}
]
}
有人可以帮我搞定吗?
解决方法:
不确定这是不是最好的方法,但它解决了你的问题.
创建转换器
internal class MyConverter : CustomCreationConverter<IDictionary<CustomClass, List<String>>>
{
public override IDictionary<CustomClass, List<String>> Create(Type objectType)
{
return new Dictionary<CustomClass, List<String>>();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof (object) || base.CanConvert(objectType);
}
}
将其添加到您的设置:
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ContractResolver = new DictionaryAsArrayResolver(),
Converters = new JsonConverter[] {new MyConverter()}
};
请享用.
内容总结
以上是互联网集市为您收集整理的c# – 使用IDictionary>的自定义解析程序进行反序列化问题全部内容,希望文章能够帮你解决c# – 使用IDictionary>的自定义解析程序进行反序列化问题所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。