Denote properties of class to not be serialized - c#

I'm using silverlight on WP7.
I have a class I am trying to serialize to isolatedstorage. I know the framework will take care of serializing the class automatically for me, assuming every property is serializable.
For this class, I have some properties (such as BitmapImage) that are not serializable. Is there a way to tell the framework to NOT serialize that property (and instead, set it as null when it deserializes it?)
I know implementing XmlSerializable is a possibility, but I don't want to have to set/get each manually. I'd rather it serialize what I tell it to, and I can go and set the other properties after it has deserialized.
thanks

You can use XmlIgnoreAttribute to tell XmlSerializer to ignore your property.

Related

Json.net failing to load certain properties belonging to a class object?

NOTE: I'm adding this community wiki entry to save someone the loss of time I just went through debugging this problem.
I have a class object with multiple public properties. I can serialize it fine using JSON.net. But when I load the JSON text back and deserialize it using JsonConvert.DeserializeObject<>, some of the fields are set to NULL when they definitely had valid values at the time of serialization. I inspected the serialized JSON string manually and I definitely see values for the NULL properties in the text. Why is this happening?
By default, Json.Net serializes and deserializes only the public members of a class. If you have public getters but private setters for your properties then the properties will be serialized to JSON but not deserialized back to your class.
The easy way to fix this is to make your setters public, but of course that breaks the immutability that private setters provide. If you want to be able to keep your setters private while still being able to deserialize them, you can annotate your properties with [JsonProperty] attributes instead. This will allow the deserializer to "see" them.
Here is a short fiddle to demonstrate: https://dotnetfiddle.net/4nZdGJ
Although it took me a while to hunt down the problem, the answer was simple. The object properties that always had NULL values when deserialized had private setters. I made the setters public and the problem went away.

Possible to add a property to a JSON version of my class without it existing in the class?

I have a List<> of objects. Their class doesn't have a 'colour' property (String) - but I can derive the value of this property for each list element right before serializing.
Is the only way to include this property in the JSON object to add it to the class and then serialize the whole thing?
Or is there a way/approach to adding a property that needs to appear in a JSON object that would otherwise be pretty useless in my class?
I know it's possible with all sorts of string manipulation methods but it doesn't feel right doing that.
I'm using DataContractJsonSerializer.
You can create a data contract surrogate that transparently substitutes instances of your class with instances of another class. This new class can look like anything, but in your case it would simply have the additional Colour property.
The benefit here is that you keep the original type of the list items; the surrogates get created during the serialization process and your existing code will not need to touch them at all.
I supose you can create a new class that inherits from your List of objects and adds the string that's unuseful on the principal class.
When creating the JSON just use the derived class, which will contain the added string value and inherits all the rest data from the original object.

JSON.NET - exclude properties of a specific type at runtime

I'm wondering how to exclude/strip certain properties of given type(s) (or collections of those) from being serialized using Json.NET library?
I tried to write my own contract resolver (inheriting from DefaultContractResolver) with no luck.
I know that I could be done using DataAnnotations, decorating the excluded properties with ScriptIgnoreAttribute, but it's not applicable in my scenario. The objects serialized can be virtually anything, so I don't know which properties to exclude at design-time. I know only the types of properties that should not be serialized.
It looks like a rather simple task, but unfortunately I couldn't find a decent solution anywhere...
BTW - I'm not bound to Json.NET library - if it can easily be done with default/other .NET JSON serializers it'd be an equally good solution for me.
UPDATE
The properties has to be excluded before trying to serialize them. Why?
Basically, the types of objects I'm receiving and serializing can have dynamic properties of type inheriting from IDynamicMetaObjectProvider. I'm not going to describe all the details, but the DynamicMetaObject returned from GetMetaObject method of these objects doesn't have DynamicMetaObject.GetDynamicMemberNames method implemented (throws NotImplementedException...). Summarizing - the problem is those objects (I need to exclude) doesn't allow to enumerate their properties, what Json.NET serializer tries to do behind the scenes. I always end up with NotImplementedException being thrown.
I have tried both the WCF JSON serialization as well as the System.Web.Script.Serialization.JavaScriptSerializer. I have found if you want solid control of the serialization process and do not want to be bound by attributes and hacks to make things work, the JavaScriptSerializer is the way to go. It is included in the .NET stack and allows you to create and register JavaScriptConverter subclasses to perform custom serialization of types.
The only restriction I have found that may cause you a problem is that you cannot easily register a converter to convert all subclasses of Object (aka, one converter to rule them all). You really need to have knowledge of common base classes or preregister the set of types up front by scanning an assembly. However, property serialization is entirely left up to you, so you can decide using simple reflection which properties to serialize and how.
Plus, the default serialization is much much much better for JSON than the WCF approach. By default, all types are serializable without attributes, enums serialize by name, string-key dictionaries serialize as JSON objects, lists serialize as arrays, etc. But for obvious reasons, such as circular trees, even the default behavior needs assistance from time to time.
In my case, I was supporting a client-API that did not exactly match the server class structure, and we wanted a much simpler JSON syntax that was easy on the eyes, and the JavaScriptSerializer did the trick every time. Just let me know if you need some code samples to get started.
Create your own contract resolver, override the method that creates the properties for an object and then filter the results to only include those that you want.
Have you considered using the ShouldSerialize prefix property to exclude the property of your specific type at runtime?
public class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
public bool ShouldSerializeManager()
{
return (Manager != this);
}
}

How to store User defined data type through DataContext?

I used DataContractSerializer to save user data but now
I want to use DataContext for my database design.
But the system existed struture as below cannot be stored through DataContext.
class Data
{
public DataType1;
public DataType2;
}
It seems these APIs cannot support storing user defined data type.
I don't want to separate all data members because this system uses these structure every where. If I changed the structure, it is hard to maintain and the DataType1 contains a List<> member. I don't know how to do even though separating
this structure.
Could you please kindly to give me some suggestions?
Thanks.
It seems these APIs cannot support storing user defined data type
If that were true the api would be completely without purpose.
The DataContractSerializer has what appear to be conflicting rules in an attempt to make serialisation more implicit. You can for example serialise a public type that has public properties and a public default constructor without having to decorate it with a DataContract attribute or any of its members with a DataMember attribute.
Looks to me that at the very least you need make Data a public class. Most likely you would need to review your other classes to ensure that either they are implicitly serializable or that you explictly mark them up with the DataContract and DataMember attributes.
Dear all:
But now I used DataContext
DataContext cannot serialize the user defined type even marked [Serializable].
The workaround seems to separate all the members into one class now.....
Thanks.

Defining the fields to be exposed (serialized) not via DataMemberAttribute

I have an autogenerated class, which I want to partially reuse as DataContract. Since the class is periodically auto-regenerated, I wouldn't like to add DataMemberAttribute to its properties, because it will be lost. What are the alternatives? Can I define which properties are going to be serialized programmatically or, may be, via a partial class?
Thanks!
You can add XmlAttributes at runtime with the XmlAttributeOverrides class but I'm not sure if you can do the same with DataMemberAttribute, have not come across an equivalent of XmlAttributeOverrides..

Categories

Resources