Overview of ExpandoObject Object JSON serialization

Source: Internet
Author: User
Tags json serialization

If:

Dynamic expando = new ExpandoObject ();

D.someprop=somevalueorclass;

And then, we're in the controller:

return new Jsonresult (expando);

Well, our front desk will get:

[{' Key ': ' Someprop ', ' Value ': Somevalueorclass}]

And in fact, we know that JSON-formatted content should be like this:

{Someprop:somevalueorclass}

So, we need a custom serializer, which should be as follows:

public class Expandojsonconverter:javascriptconverter
{public
    override ienumerable<type> Supportedtypes
    {
        get
        {return
            new readonlycollection<type> (new type[] {typeof ( System.Dynamic.ExpandoObject)});
        }
    
    public override object Deserialize (idictionary<string, object> dictionary, type type, JavaScriptSerializer Serializer)
    {
        throw new notimplementedexception ();
    }
    
    public override Idictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer)
    {
        var result = new dictionary<string, object> ();
        var dictionary = obj as idictionary<string, object>;
        foreach (var item in dictionary)
        {result
            . ADD (item. Key, item. Value);
        }
    
        return result;
    }

Now, our controller should write like this:

Public Contentresult getsomething (string categores)
{return
    controllproctector.do1 (() =>
        {
    
            ...)
            var serializer = new JavaScriptSerializer ();
            Serializer. Registerconverters (new javascriptconverter[] {new Expandojsonconverter ()});
            var json = serializer. Serialize (expando);
            return new Contentresult
            {
                Content = json,
                ContentType = ' Application/json '
            };
}

Back to the column page: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.