开发者

serializing only parts of an object with json

I have an object called MyObject that has several properties. MyList is a list of MyObject that I populate with a linq query and then I serialize MyList into json. I end up with something like this

    List<MyObject> MyList = new List<MyObject>();

    MyList = TheLinqQuery(TheParam);

    var TheJson = new System.Web.Script.Serialization.JavaScriptSerializer();
    string MyJson = TheJson.Serialize(MyList);

What I want to do is serialize only parts of MyObject. For instance, I might have Property1, Property2...Propertyn and I want MyJson to only include Property3, Prope开发者_高级运维rty5 and Property8.

I thought of a way to do this by creating a new object with only the properties I want and from there create a new list for the serialization. Is this the best way or is there a better/faster way?

Thanks.


// simple dummy object just showing what "MyObject" could potentially be
public class MyObject
{
    public String Property1;
    public String Property2;
    public String Property3;
    public String Property4;
    public String Property5;
    public String Property6;
}

// custom converter that tells the serializer what to do when it sees one of
// the "MyObject" types. Use our custom method instead of reflection and just
// dumping properties.
public class MyObjectConverter : JavaScriptConverter
{
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        throw new ApplicationException("Serializable only");
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        // create a variable we can push the serailized results to
        Dictionary<string, object> result = new Dictionary<string, object>();

        // grab the instance of the object
        MyObject myobj = obj as MyObject;
        if (myobj != null)
        {
            // only serailize the properties we want
            result.Add("Property1", myobj.Property1);
            result.Add("Property3", myobj.Property3);
            result.Add("Property5", myobj.Property5);
        }

        // return those results
        return result;
    }

    public override IEnumerable<Type> SupportedTypes
    {
        // let the serializer know we can accept your "MyObject" type.
        get { return new Type[] { typeof(MyObject) }; }
    }
}

And then where ever you're serializing:

// create an instance of the serializer
JavaScriptSerializer serializer = new JavaScriptSerializer();
// register our new converter so the serializer knows how to handle our custom object
serializer.RegisterConverters(new JavaScriptConverter[] { new MyObjectConverter() });
// and get the results
String result = serializer.Serialize(MyObjectInstance);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜