我创建了一个包含多态值的字典,其中保存了一个类对象。我已成功序列化 JSON。但我无法反序列化它。它给出以下错误:
Element ':Value' contains data of the ':Sale' data contract. The deserializer has no knowledge of any type that maps to this contract.
如果将 JSON 属性
我的代码如下:
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 63 64 65 66 67 68 69 70 71 72 73 74 75 | using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; class Program { static void Main(string[] args) { Dictionary<string, object> dict = new Dictionary<string, object>(); dict.Add("employee","john"); dict.Add("sale",new Sale(9,5243)); dict.Add("restaurant",new Restaurant("Cheese Cake Factory","New York")); // Console.Write(dict["sale"]); //Code for JSON DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Dictionary<string, object>)); MemoryStream msObj = new MemoryStream(); js.WriteObject(msObj, dict); msObj.Position = 0; StreamReader sr = new StreamReader(msObj); string json = sr.ReadToEnd(); sr.Close(); msObj.Close(); // Decode the thing Console.Write(json); Dictionary<string, object> result = new Dictionary<string, object>(); using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<string, object>)); result = serializer.ReadObject(stream) as Dictionary<string, object>; } } } [DataContract] [KnownType(typeof(Sale))] public class Sale { [DataMember(Name ="SaleId")] public int SaleId {get; set;} [DataMember(Name ="Total")] public int Total{ get; set;} public Sale(int saleid, int total) { SaleId = saleid; Total = total; } public int getTotal() { return Total; } } [DataContract(Name ="Restaurant", Namespace="")] [KnownType(typeof(Restaurant))] public class Restaurant { [DataMember(EmitDefaultValue = false)] public string Name {get; set;} [DataMember(EmitDefaultValue = false)] public string City{get; set;} public Restaurant(string name, string city) { Name = name; City = city; } } |
小提琴链接:https://dotnetfiddle.net/CfQxxV
您正在尝试使用多态成员序列化根对象
那么,如何使用您的数据模型来做到这一点?有几种方法:
将
的答案所示
这不能在这里工作,因为基本类型是
将
这看起来有问题,因为您的根对象类型是
2 3 4 5 | [KnownType(typeof(Restaurant))] public class ObjectDictionary : Dictionary<string, object> { } |
然后使用这个子类构造和序列化你的字典:
2 3 4 5 6 7 8 | { {"employee","john" }, {"sale",new Sale(9,5243) }, {"restaurant",new Restaurant("Cheese Cake Factory","New York")}, }; DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(ObjectDictionary)); |
这里是演示小提琴#1。
通过使用
中指定
2 3 4 5 | { KnownTypes = new [] { typeof(Sale), typeof(Restaurant) }, }; DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Dictionary<string, object>), settings); |
确保为序列化和反序列化以相同的方式配置序列化程序。
这里是演示小提琴#2。
(对于 XML,使用
通过配置文件指定其他已知类型,如添加已知类型的其他方法中所示。
您是直接序列化,但如果您是通过 WCF 进行序列化,则可以将
永远不需要将
2 3 4 5 6 | //[KnownType(typeof(Sale))] Remove this public class Sale { // Remainder unchanged } |
有关更多信息,请参阅 Sowmy Srinivasan 的所有关于 KnownTypes。
您遇到的问题是您将
使用 KnownType 的原因是为了在 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 | [KnownType(typeof(Restaurant))] [KnownType(typeof(Employee))] [DataContract] public class SomeObject { } [DataContract(Name ="Sale", Namespace="")] public class Sale : SomeObject { //methods + properties + variables } [DataContract(Name ="Restaurant", Namespace="")] public class Restaurant : SomeObject { //methods + properties + variables } [DataContract(Name ="Employee", Namespace="")] public class Employee: SomeObject { //methods + properties + variables } |
然后使用字典作为
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e
我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)
我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类
当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub