views:

60

answers:

1

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 serialization 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?

A: 

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; }
}
Artiom Chilaru
I hadn't tried a custom resolver. However I like my main problem is Bar inherits from ConfigurationElement, which throws everything off.
BozoJoe
Well.. What's the problem in that? You can go through the ConfigurationElement in the Serialize method and add the values you want in the dictionary result.. Or you're looking for something else?
Artiom Chilaru
@Artiom - Using the customer resolver is just moving the problem state into the resolver code rather than in the DTO/Assembler code. The Resolver idea does give me a different entry point, which is nice, thx. Really I think I need something to get my custom config class into a POCO serializable object graph.
BozoJoe