I need to take a portion of my xxx.config custom configuration and serialize it as JSON directly into my page.
Using DataContractJsonSerializer yields
{"LockItem":false}
Which is similar to the response from XmlSerializer. I can't seem to find an override that gives me control over the se开发者_JAVA百科rialization process on System.Configuration classes. Are there any good techniques for this, for should I just create a set of DTO'ish mimic classes and assemble data into them for serialization?
As I understand you want to be able to manually serialize the object, while still benefiting from the .NET to Json serialization classes.
In this case you can use the JavaScriptSerializer class. You can register a convertor for this class in which case you have full control over the serialization of the object you're passing. The Serialize method that you override returns a simple IDictionary, which will then be directly serialized to json..
Here's an example of what it looks like..
void Main()
{
var js = new JavaScriptSerializer();
js.RegisterConverters(new[] { new PonySerializer() });
js.Serialize(new Bar { Foo = 5 }).Dump();
}
public class PonySerializer : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new [] { typeof(Bar) }; }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var result = new Dictionary<string, object>();
if (obj is Bar)
{
var ob = obj as Bar;
result["Foo"] = ob.Foo;
}
return result;
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
}
public class Bar
{
public int Foo { get; set; }
}
精彩评论