0

I'm trying to find a simple way to serialize any object so that only the immediate properties and their "ToString" values are included. In the case of an object coming from a DataContext I want to be able to ignore properties of properties (ie. if a property is a complex object, don't serialize that object as well). This is especially important if the properties are not loaded since it causes an error "Cannot access an object after it has been disposed"...

I created the following but it fails when it tries to access a property that wasn't loaded in the original datacontext call.

string typeString = o.GetType().Name;
        StringBuilder xml = new StringBuilder();
        xml.AppendFormat("<{0}>\r\n", typeString);

        foreach (PropertyInfo property in o.GetType().GetProperties())
        {
            var propertyValue = property.GetValue(o, null);
            if (property.GetType() != typeof(System.Data.Linq.Binary) && property.PropertyType.Name != "EntitySet`1" && property.GetCustomAttributes(typeof(XmlIgnoreAttribute), true).Count() == 0)
            {
                xml.AppendFormat("<{0}>{1}</{0}>\r\n", property.Name, propertyValue);
            }

        }

        xml.AppendFormat("</{0}>", typeString);

        return xml.ToString();
Chad H
  • 584
  • 3
  • 11

1 Answers1

1

You can use a stock serializer with appropriate "ignore" attributes, e.g. use DataContractSerializer and the IgnoreDataMemberAttribute on properties you do not wish to have serialized.

If you wish to stick with the approach you outline, you can check PropertyInfo.PropertyType to not act on anything that is a complex type.

You can use Type.IsPrimitive to see if a given type is primitive or not, but there are a few gotcha's that are well-covered here:

https://stackoverflow.com/a/2442544/141172

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • I want to avoid tagging classes with "IgnoreDataMember". Essentially I want a snapshot of the object I pass to it so how would I go about using the PropertyType to filter out "complex types", would I need to say where type = int, or string, or.. etc? – Chad H Mar 20 '13 at 23:40
  • Updated the answer accordingly. – Eric J. Mar 20 '13 at 23:47
  • This is great. It fixes the datacontext issue too, although ideally I could still have "loaded" properties that are complex types show up using "ToString". But I'll take what I can get. – Chad H Mar 21 '13 at 00:29