使用 JavascriptSerializer 将自定义类型属性序列化为字符串
我现在使用 .NET JavascriptSerializer 类一段时间,将我的对象序列化为 JSON 表示形式并在客户端使用它。只要我坚持使用 int、string 等默认类型,一切都会很好。但是,现在我想在我的对象上序列化自定义类型属性。让我们看一下我的类的一个例子:
public class ClientData
{
public Guid Id { get; set; }
public string Description { get; set; }
public MyCustomObject ObjectX { get; set; }
}
我想要的 Wat 是一个客户端对象,看起来像这样:
{ Id: 0000-0000-000-0000, Description: "some description", ObjectX: "125.20" }
为了使这个工作正常,我尝试使用 JavaScriptConverter 但这似乎不能解决问题,因为它只能处理字典,什么将使结果看起来像这样:
{ Id: 0000-0000-000-0000, Description: "some description", ObjectX: { Value: "125.20"} }
这不是我想要的。顺便说一句,我确实在 MyCustomObject 类上实现了 toString 。
有什么建议吗?
谢谢分配。
I am using the .NET JavascriptSerializer class for a while now to serialize my object to a JSON representation and use it on the client side. Everything works great as long as I stick with the default types like int, string, etc. However, now I want to serialze a custom type property on my object. Let look at an example of my class:
public class ClientData
{
public Guid Id { get; set; }
public string Description { get; set; }
public MyCustomObject ObjectX { get; set; }
}
Wat I want is a clientside object that looks something like this:
{ Id: 0000-0000-000-0000, Description: "some description", ObjectX: "125.20" }
To make this work, I tried using a JavaScriptConverter but that doesn't seem to solve the problem because it can only handle dictionaries, what will make the result look like this:
{ Id: 0000-0000-000-0000, Description: "some description", ObjectX: { Value: "125.20"} }
That's not what I want. I did implement the toString on the MyCustomObject class by the way.
Any suggestions?
Thanks allot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 Json.NET 库中的 JsonConverter 似乎对我有用。
Using a JsonConverter from the Json.NET library seems to do the trick for me.
您可以将自定义对象转换为字符串。您使用 JavaScriptConverter 将对象转换为 Uri 实例,该实例还实现 IDictionary 以允许它从 JavaScriptConverter 传递出去。
此处针对 DateTime 对象描述了此技巧:
http://blog.calyptus.eu/seb/2011/ 12/自定义日期时间json序列化/
You can convert a custom object into a string. You use a JavaScriptConverter that converts your object into a Uri instance that also implements IDictionary to allow it to pass out of the JavaScriptConverter.
This hack is described for DateTime objects here:
http://blog.calyptus.eu/seb/2011/12/custom-datetime-json-serialization/
这是 javascriptserializer 的 msdn 页面:
http://msdn.microsoft.com/en -us/library/system.web.script.serialization.javascriptserializer.aspx
在备注部分说:
所以你应该看看这个类:
http://msdn.microsoft.com/en -us/library/system.web.script.serialization.javascriptconverter.aspx
here is the msdn page to javascriptserializer:
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
in the remark section it says:
so you should look at this class:
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptconverter.aspx