Update a single element of a xml serialized by DataContractserializer in C#? - c#

I have a class, which is serialized using the DataContractSerializer class. Now I want to update a single property (a string) of the serialized object.
For some reason, I can't find a functionality for this, so my only option would be to serialize the complete object - which can get quite big. It seems a bit of overkill to serialize several hundreds of lines just to change a single string element.
Is there no better approach to this?

Related

Object Serialization to Dictionary per propertyname

I asking this mostly to see if there is something that ressembles what I am trying to achive.
My ultimate goal is to serialize an object graph, keeping references, but making all the properties accessible via a Path of sorts.
My first thoughts were something like dictionary and recursively loop through all the objects properties/fields, and if the value is different than the Default one, try and serialize if its a primitive, otherwise keep going till the type can be serialized.
I need to support Types not marked as [Serializable], and to be able to add custom serialization, similiar to how surrugates work in the BinaryFormatter.
Is there a serializer that works remotely like I said?
Or what other caveats can you think of, by this aproach?
Note: The serialization Size is not a big issue nor is the speed that it serializes/deserializes, at least for now.
An example of what I want to to is something like this :
SerializationContext.GetValue["root/Prop/X"] returns me the X value.
This needs to work with .Net 3.5, and it should serialize based on field/property name.

How to dynamically create a JSON object in c# (from an ASP.NET resource file)?

I need to serialize the strings from a resource file (.resx) into a JSON object. The resource file's keys are in flux and thus I cannot just create a C# object that accepts the appropriate values. It needs to be a dynamic solution. I am able to loop through the key-value pairs for the file, but I need an easy way to serialize them to JSON.
I know I could do:
Object thing = new {stringOne = StringResource.stringOne; ...}
But, I'd rather have something like:
Object generic = {}
foreach (DictionaryEntry entry in StringResource) {
generic.(entry.Key) = entry.Value
}
Or should I just create a custom JSON serializer that constructs the object piecemeal (i.e. foreach loop that appends part of the JSON string with each cycle)?
EDIT
I ended up writing a quick JSON serializer that constructs the string one field at a time. I didn't want to include a whole JSON library as this is the only use of JSON objects (for now at least). Ultimately, what I wanted is probably impractical and doesn't exist as it's function is better served by other data structures. Thanks for all the answers though!
If you're using C# 4.0, you should look at the magical System.Dynamic.ExpandoObject. It's an object that allows you to dynamically add and remove properties at runtime, using the new DLR in .NET 4.0. Here is a good example use for the ExpandoObject.
Once you have your fully populated ExpandoObject, you can probably easily serialize that with any of the JSON libraries mentioned by the other excellent answers.
This sounds like an accident waiting to happen (i.e. creating output prior to cementing the structure), but it happens.
The custom JSON serializer is a compelling option, as it allows you to easily move from your dictionary into a JSON format. I would look at open source libraries (JSON.NET, etc) to see if you can reduce the development time.
I also think setting up in a slightly more structured format, like XML, is a decent choice. It is quite easy to serialize from XML to JSON using existing libraries, so you avoid heavy customization/
The bigger question is what purposes will the data ultimately serve. If you solve this problem using either of these methods, are you creating bigger problems in the future.
Probably I would use JSON.NET and the ability to create JSON from XML.
Then, you could create an XML in-memory and let JSON.NET convert it to JSON for you. Maybe if you dig deeper into the API, there are other options, too.
Newtonsoft is a library that has all kinds of nifty JSON tools...among them, on-the-fly one-line serializer and deserializers...check it out, it's my favorite JSON library out there
http://james.newtonking.com/pages/json-net.aspx
If I remember correctly, it has a class that will convert JSON to a .NET object without having to create the .NET object first. Think it is in the Json.Convert class
The way I do it is:
var serialiser = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = serialiser.Serialize(data);
context.Response.Write(json);

Deserialize XML with different schemas into a shared type

Using c#, I want to deserialize xml from various sources into objects of a common type. The XML will not have the same schema. Eg, in the following xml, /thingContainer/thing/name and widget/#title both would map to myClass.DisplayName.
Xml1:
<thingContainer>
<thing>
<name>MyName</name>
</thing>
</thingContainer>
Xml2:
<widget title="myTitle" />
So, I can't mark up my class with [XmlElement], since it will be different depending on the source of my xml. Is there some trick I can do with inheritance or some helper class that will enable me to easily deserialize xml from different sources? Is there some easy way to map class fields to xpaths?
Of course, if I have to, I'll parse and manually deserialize the xml... but what fun is that?
Two thoughts that immediately spring to mind:
Use XSLT to transform the original XML into an interim format that matches your object model (a very popular approach, though personally I despise XSL)
Create interim object models to deserialize to, then map them to your final object model.
There's probably some XmlElement hackery possible, but it seems like it would be a messy approach.
I think you have two options here:
Implement IXmlSerializable for your class and deserialize taking into account the structure of your XML
Just use LINQ to XML to parse the XML and create an instance of your class. This is the approach I would pick (having gone through the first choice myself and not liking it)

Slightly non-trivial data structure: is XmlSerializer right for me?

I'm currently using XmlSerializer to, surprisingly enough :), handle de/serialization of my data structures - I find it wonderfully simple to use, but at the cost of flexibility. At the moment, I'm using it for a tree-based structure; since XmlSerializer doesn't handle cyclic structures, I've added [XmlIgnore] to my Parent property, and do a post-deserialization iteration over the tree to fix up node parents.
Is there a better way to handle this using XmlSerializer, or would it be better to rewrite the code using XmlReader/XmlWriter? I suppose implementing IXmlSerializable would work, but it seems like a fair amount of work, while still retaining the cons of XmlSerializer.
The current post-deserialization step is OK, but I'm adding a data structure that has to be serialized to a separate XML file: basically a flat list of items that need a Parent property referencing a node from the previous tree structure. This would require yet a post-deserialization step, as well as keeping both a Parent attribute as well as as ParentId (or some trickery) in the new data structure.
So, any smart (and non-fragile) ideas? Or XmlReader/XmlWriter it is?
Solution
DataContractSerializer turned out to be a pretty decent solution, with pretty much the same simplicity as XmlSerializer. I opted not to use the automatic cycle handling but instead defining and OnDeserialized decorated method to handle setting the parent node; that way, the generated XML is standard-conforming.
One thing that confused me for a while was that I got crashes on some properties after deserializing, with the backing members set to null - couldn't figure out how this was possible since the backing members were definitely initialized in all possible constructors. Debugging showed constructors were never called, and after some googling I found this SO post with an explanation.
You could try binary serialization (BinarySerializer or DataContractSerializer), which I think handles cyclic graphs somewhat better, at the cost of not having a human-readable representation of the data. Alternatively, you can try the SoapFormatter as detailed here.
Use DataContractSerializer. Mark your classes with [DataContract(IsReference = true)].

Is there an XML specific object (like XElement) that is binary serializable?

I have a use case where I am serializing objects over the wire via MSMQ (mostly strings). When I read the object off the queue I want to be able to tell if the user meant for the object to be a XML or a string. I was thinking a good way to do this would just be to check the type. If it's XmlElement than it becomes XML data otherwise it becomes string or CDATA. The reason I don't want to just check to see if the data is valid XML is that sometimes data will be provided that is supposed to be serialized as a string but is in fact valid XML. I want the caller to be able to control the de-serialization into string or XML.
Are there any types that are marked as serializable in the .NET Framework like XElement or XmlElement (both which are not marked serializable)?
Why don't you just add a property to the class of the serialized object that tells you what it is? I'd propose IsXml.

Categories