开发者

Serialize custom type property to string using JavascriptSerializer

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.


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:

To serialize an object, use the Serialize method. To deserialize a JSON string, use the Deserialize or DeserializeObject methods. To serialize and deserialize types that are not natively supported by JavaScriptSerializer, implement custom converters by using the JavaScriptConverter class. Then register the converters by using the RegisterConverters method.

so you should look at this class: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptconverter.aspx


Using a JsonConverter from the Json.NET library seems to do the trick for me.


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜