使用catchalldictionary属性将json序列化成一个对象我想用json.net反序列化成一个对象,但是未映射的属性放到了字典属性。是否可以?例如对于json,{one:1,two:2,three:3}和c#类:publicclassMapped{publicintOne{get;设置;}publicintTwo{get;设置;}公共字典TheRest{get;set;}}JSON.NET可以反序列化为一个实例,其值为1=1,2=1,TheRest=Dictionary{{"three,3}}你可以创建一个CustomCreationConverter来做你需要做的事情。这是一个样本(相当难看,但表现了你可能想要这样做):namespaceJsonConverterTest1{publicclassMapped{privateDictionary_theRest=newDictionary();publicintOne{得到;放;}publicintTwo{get;放;}publicDictionaryTheRest{get{return_theRest;}}}publicclassMappedConverter:CustomCreationConverter{publicoverrideMappedCreate(TypeobjectType){returnnewMapped();}publicoverrideobjectReadJson(JsonReaderreader,TypeobjectType,objectexistingValue,JsonSerializerserializer){varmappedObj=newMapped();varobjProps=objectType.GetProperties().Select(p=>p.Name.ToLower()).ToArray();//returnbase.ReadJson(reader,objectType,existingValue,serializer);while(reader.Read()){if(reader.TokenType==JsonToken.PropertyName){字符串readerValue=reader.Value.ToString().ToLower();if(reader.Read()){if(objProps.Contains(readerValue)){PropertyInfopi=mappedObj.GetType().GetProperty(readerValue,BindingFlags.IgnoreCase|BindingFlags.Public|BindingFlags.Instance);varconvertedValue=Convert.ChangeType(reader.Value,pi.PropertyType);pi.SetValue(mappedObj,convertedValue,null);}else{mappedObj.TheRest.Add(readerValue,reader.Value);}}}}返回映射对象;}}publicclassProgram{staticvoidMain(string[]args){stringjson="{'one':1,'two':2,'three':3,'four':4}";映射的mappedObj=JsonConvert.DeserializeObject(json,newMappedConverter());Console.WriteLine(mappedObj.TheRest["三"].ToString());Console.WriteLine(mappedObj.TheRest["四"].ToString());所以在反序列化JSON字符串之后,mappedObj的输出将是一个对象,其中One填充了One和Two属性,而字典中的其他所有内容当然我把One和Two值硬编码为int,但我认为这证明了你是如何去做的。我希望这有帮助。编辑:我更新了代码以使其更通用。我还没有完全测试它,所以它在某些情况下会失败,但我认为它会让你大部分时间都在那里。最简单的方法是使用JsonExtensionData属性定义一个catchall字典。Json.Net文档中的例子:以上是C#学习教程:使用catchall字典属性将json序列化为一个对象来共享所有的内容。如果对大家有用,需要详细了解C#学习教程,希望大家多多指教Follow--publicclassDirectoryAccount{//正常反序列化publicstringDisplayName{get;放;}//这些属性在OnDeserialized中设置publicstringUserName{get;放;}公共字符串域{得到;放;}[JsonExtensionData]privateIDictionary_additionalData;[OnDeserialized]privatevoidOnDeserialized(StreamingContextcontext){//SAMAccountName未反序列化为任何属性//因此它被添加到扩展数据字典中stringsamAccountName=(string)_additionalData["SAMAccountName"];域=samAccountName.Split('\')[0];用户名=samAccountName.Split('\')[1];}publicDirectoryAccount(){_additionalData=newDictionary();}}stringjson=@"{'DisplayName':'JohnSmith','SAMAccountName':'contoso\johns'}";DirectoryAccount帐户=JsonConvert。反序列化对象(json);安慰。WriteLine(account.DisplayName);//JohnSmithConsole.WriteLine(account.Domain);//ContosoConsole.WriteLine(account.UserName);//johns本文摘自网络,不代表立场。如涉及侵权请点击维权联系管理会员删除如需转载请注明出处:
