I have few .cs files generated by xsd.exe by a XSD schema.
My problem is that when i try to serialize those classes to xml, the attributes whose values match the default values defined in the xsd schema are not being serialized.
I found out that my problem is solved when i remove [System.ComponentModel.DefaultValueAttribute(typeof(<someType>), "<SomeValue>")]
attribute for the member representing a default field.
So my question isn't there more elegant way to do this? For example is there any way to specify that I want the default values to be serialized anyway?
The short versions is: yes. it looks like that is the simplest approach.
I've tried the "obvious" things (in particular the *Specified and ShouldSerialize* patterns that XmlSerializer supports, but also IsNullable) and it just keeps on not including the value.
The next options would be either IXmlSerializable (which is plain hard), or XmlAttributeOverrides (a duplication of effort) - neither of which is particularly enticing here. I wonder if your current approach is less work? You could of course simply export the WSDL and edit that to remove the default (and generate from the edited version).
As an aside - if this was WCF, there is the [DataMember(EmitDefaultValue = ...)] that does control this; maybe they added this as a feature request?
Related
I have a Json schema and can use NJsonSchema.CodeGeneration.CSharp to create classes corresponding to it. So if I have json which conforms to the schema, I should be able to easily parse it into a collection of objects whose classes are the classes generated from the schema?
So how can I do this - parse json and get out C# class objects that correspond to the objects in the json (as define by the schema)?
As an example - if the schema defines a first object definition which is an array of a second object definition, then I would like to be able to parse it in such a way that the output is an instance of the class corresponding to the first object definition and it has a member which is a List of instances of the class corresponding to the second definition. It seems that the schema knows all the information required to do this, so it should be a single line - I appreciate I could do long-hand parsing (eg converting each item in the array) to achieve the same result.
I would think this would be a primary purpose of having C# classes generated from a schema, so what's the magic method I'm missing?
I'm also happy to write C# classes and generate a schema from that if it's a more workable solution.
I've used NJsonSchema but happy to use any other C# json schema and code generation technique that achieves the same end.
UPDATE: After discussion I've seen that if NJsonSchema is used to generate classes from the schema, the TypeScript version of those classes each have a fromJS method which sounds like what I want but they're missing from the C# version. I'm happy to use something other than NJsonSchema to generate classes from schema if it provides a solution.
I think I found the answer, which was a lot simpler than I had anticipated. It's simply to use something like:
var ob=JsonConvert.DeserializeObject<MyNamespace.Anonymous>(jsonString);
...where MyNamespace is the namespace of the generated C# classes, MyNamespace.Anonymous is the class corresponding to the root of the schema (default names from NJsonSchema), and jsonString the string to be parsed.
I thought the solution would need to be schema-aware, since it would need to know about all the classes created from the schema, but I guess it 'works that out' from reflecting on the Anonymous class it's given and where the properties of it are classes, reflecting on those and so on.
I was over-thinking the problem!
I'm looking for a Serializer to persist my classes in text format (not binary). But...
I'm already using protobuf for binary serialization. It works pretty fine. As a side note, I would have prefer not to deal with field id (index) like with protobuf.
Before closing or voting to close this question, please consider these points:
The specificity of this question
If other question really apply to my requirements and are not too old
I'm looking for a serializer with the following properties:
Easy to use
Serialize in text (readable) either Json or XML would be fine
Free
Is documented
Support versioning easily (obsolete field, type change, property name change, ...)
Uses Attribute to define items to serialize (or not serialize)
Does not uses an index (ID like Protobuf)
Be able like Protobuf, to deserialize an object directly without any constructor. Be able to instanciate an object either if the object does not have any public constructor and does not have any constructor with no arguments.
Does not require me to change my class or member accessibility, ie:
Does not need default constructor
Can serialize fields
Can skip public property (when marked to do so)
Others points not essential:
The speed is not important
Open source is a nice bonus
Has some examples is a nice bonus
Some examples of what I prefer to not use:
Microsoft XMLSerializer and JsonSerializer does require default constructor.
I have hard time using Microsoft-DataContractSerializer, an easier solution would be welcome.
Does anyone know if there is an alternative to using attributes on C# properties to map to XML nodes when using XmlSerializer?
My issue is that I have an object called Article, with some properties (e.g. ID, Title, Body) and I do not want to add attributes directly to it (used elsewhere, etc, etc)...so I created a partial class and re-defined the properties and added the attributes there, but soon discovered that you cannot have duplicate properties in partial classes.
So I was wondering if anyone knew of any way that I could map the properties instead (in a similar fashion to n-hibernate, for example).
I'd appreciate any help.
There's a constructor of the XmlSerializer class that allows you to pass a XmlAttributeOverrides and thus alter the behavior at runtime.
Quote from the documentation:
The overrides parameter can be used to control how fields and
properties are encoded in XML. These settings override any attributes
that already exist on the objects. This can be useful when the source
code cannot be modified or multiple encodings are required for the
same classes.
You could implement IXmlSerializable directly. It requires some more code, but you will have full control without the need for attributes.
My program creates xslt files and stores the information from custom classes there, this is done dynamically with attributes which mark the classes and properties I want to store in the xslt. This was quite easy because i just had to name the attribute like the property and fill the value with the object's toString() method.
Now I want to somehow reload that Information, create the same classes and fill the properties with those values. But how do i do that with e.g. Enums and other complex types if i don't know the type at compile time? Has to be some sort of parse method..
Any ideas?
If you just want to serialize your objects to XML and then desterilize them, and your objects contain interfaces, generic lists or other complex type you can use very useful serialization library http://www.codeproject.com/KB/XML/sharpserializer.aspx by Pawel Idzikowski.
It is really straight forward and can be very helpful in such cases.
Currently I'm using XmlSerializer to serialize and deserialize an object. The xml is generated in an undefined order which is understandable but makes it annoying when comparing versions of the object, since the order of properties is different each time. So for instance I can't use a normal diff tool to see any differences.
Is there an easy way to generate my xml in the same order every time, without writing the ReadXml and WriteXml methods myself? I have a lot of properties on the class, and add new ones every now and again, so would prefer to not have to write and then maintain that code.
(C# .net 2.0)
The XmlElement attribute has an order property. You can use that as a start.
If you need to find the diff in Xml files, you might want to take a look at this.
Decorate your properties with the XmlElementAttribute, setting the Order parameter.
ps: I don't believe the XML generated by the XmlSerializer is in an undefined order. It may be undocumented, but it is known. I believe that in the absence of Order attributes, the XmlSerializer serializes all public Properties, alpha-sorted by prop name, and then all public Fields, alpha-sorted by name.