C#学习教程:如何使用非标准(和变化的)属性名称反序列化JSON(在.NET中)我必须读取以下形式的JSON流(我无法控制):{"files":{"/some_file_path.ext":{"size":"1000","data":"xxx","data2":"yyy"},"/other_file_path.ext":{"size":"2000","data":"xxx","data2":"yyy"},"/another_file_path.ext":{"size":"3000","data":"xxx","data2":"yyy"},}}所以,我有一个名为文件的对象,它有很多属性,每个属性都有1)不同的名称,2)每次都有不同的数量,以及3)名称中包含不能在C#属性中使用的字符。我怎样才能反序列化它?我把它放到一个可移植的库中,所以我不能在System.Web.Script.Serialization中使用JavaScriptSerializer,而且我不确定JSON.NET。我希望使用标准的DataContractJsonSerializer。更新:我已将示例数据更改为更接近实际数据,并更正了不重要区域中的JSON语法。(仍然简化了很多,但在其他方面相当标准)您可以将“文件”对象建模为由JSON属性名称键入的字典:publicclassRootObject{publicDictionaryfiles{get;放;}}publicclassPathData{publicintsize{get;放;}公共字符串数据{得到;放;}publicstringdata2{得到;放;只有.Net4.5及以上版本才可以使用DataContractJsonSerializer反序列化,但是必须先设置DataContractJsonSerializerSettings.UseSimpleDictionaryFormat=true:varsettings=newDataContractJsonSerializerSettings{UseSimpleDictionaryFormat=true};varroot=DataContractJsonSerializerHelper.GetObject(jsonString,settings);使用辅助方法:publicstaticclassDataContractJsonSerializerHelper{publicstaticTGetObject(stringjson,DataContractJsonSerializerserializer=null){using(varstream=GenerateStreamFromString(json)){varobj=(serializer??newDataContractJsonSerializer(typeof(T))).ReadObject(流);返回(T)对象;}}publicstaticTGetObject(stringjson,DataContractJsonSerializerSettings设置ings){returnGetObject(json,newDataContractJsonSerializer(typeof(T),settings));}privatestaticMemoryStreamGenerateStreamFromString(stringvalue){returnnewMemoryStream(Encoding.Unicode.GetBytes(value??""));或者,您可以安装Json.NET并执行以下操作:varroot=JsonConvert.DeserializeObject(jsonString);Json.NET在不更改设置的情况下自动将字典序列化为JSON对象我们需要先将这个无效的JSON转换为有效的JSON。所以有效的JSON应该是这样的:“yyy”},“文件路径”:“C:\其他\文件\路径”,“文件数据”:{“大小”:2000,“数据”:“xxx”,“data2”:“yyy”},“FilePath":"C:\another\file\path","FileData":{"size":3000,"data":"xxx","data2":"yyy"}}}使其成为有效的JSON,我们可能会使用一些字符串函数使它看起来像上面那样。如MyJSON=MyJSON.Replace("\","\\");MyJSON=MyJSON.Replace("文件",""文件"");MyJSON=MyJSON.Replace("数据:",""数据:"");MyJSON=MyJSON.Replace("data2",""data2"");MyJSON=MyJSON.Replace(":{size",","FileData":{"size"");MyJSON=MyJSON.Replace("C:",""FilePath":"C:");我们可以创建如下类来读取publicclassFileData{publicintsize{get;set;}publicstringdata{get;set;}}}publicclassFiles{publicstringFilePath{get;set;}publicFileDataFileData{get;set;}}publicclassRootObject{publicFilesfiles{get;set;}}假设你有一个有效的JSON,你可以使用JavaScriptSerializer返回一个对象列表stringjson="{}"varserializer=newJavaScriptSerializer();vardeserializedValues=(Dictionary)serializer.Deserialize(json,typeof(object));或者,你可以使用Dictionary>作为类型参数以上是C#学习教程:HowtodeserializeJSON(in.NET)withnon-standard(andchanging)propertynames分享所有内容,如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——strignjson="{}";JavaScriptSerializerserializer=新的JavaScriptSerializer();vardeserializedValues=序列化器。反序列化>>(json);foreach(KeyValuePair>kvpindeserializedValues){Console.WriteLine(kvp.Key+":"+string.Join(",",kvp.Value));}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:
