How to deserialize XML attributes - c#

I can create an object to hold a deserialized xml file. Mapping Xml elements to objects is easy, i just create properties in the in the class matching the name of the element. But how can i map Xml attributes to the class. For example, if i have this:
<Typestyle name="" location="" />
I want to deserialize the name and location attributes into properties on my class?

why not use the xsd.exe tool in the .NET framework SDK to create C# class code representing the schema. Then add those classes to your project and you can use XmlSerializer with those classes without needing to write the class code yourself.
Try this http://msdn.microsoft.com/en-us/library/x6c1kb0s.aspx

Look at XmlAttributeAttribute class.
public class TypeStyle
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("location")]
public string Location{ get; set; }
}

public class Typestyle
{
[XmlAttribute]
public string name { get; set; }
[XmlAttribute]
public string location { get; set; }
}

Related

System.Json - custom rules for property serialization skipping

I am trying to migrate from Newtonsoft.Json to System.Text.Json
However, I ran into a problem since I was using DefaultContractResolver.
My "custom" behaviour have these rules for property serialization:
Skip property serialization if it is marked with ReadOnly attribute
Skip property serialization in case of null (this is supported)
Skip property serialization which would serialize into an empty object
Example:
class Car
{
[ReadOnly]
public string Id { get; set; }
public string Name { get; set; }
public Person Owner { get; set; }
}
class Person
{
[ReadOnly]
public string Id { get; set; }
public string Name { get; set; }
}
Now, imagine, we have this data if no rules would apply.
{
"Id":"1234",
"Name":"Skoda",
"Owner":{
"Id":"abcd",
"Name":null
}
}
Now, if I serialize the object, I would like to get this instead.
{
"Name":"Skoda"
}
In order to ignore individual properties, you need to use the [JsonIgnore] attribute along with one of these conditions:
Always;
Never;
WhenWritingDefault;
WhenWritingNull.
You can also define a default ignore condition through the JsonSerializerOptions type.
If additional behavior is needed, you should write a custom converter.
Example:
class Person
{
[JsonIgnore(Condition = JsonIgnoreCondition.Always)]
public string Id { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string Name { get; set; }
}
More information:
How to ignore properties with System.Text.Json
How to write custom converters for JSON serialization (marshalling) in .NET

C# XmlSerializer: Deserializing child element text value

I am having trouble deserializing my XML data into the data structures I've defined. I don't have any control over the creation of the XML, but it is structured like:
<order id="123456">
<userid>555</userid>
<merchant id="111">SomeMerchant</merchant>
</order>
I get the top level attributes and simple element values okay, but the part that is giving me issues is assigning the value of a child element to a property in a child class. My data structures look something like:
public class OrderData
{
[XmlElement("merchant", typeof(OrderMerchant))]
public OrderMerchant Merchant { get; set; }
[XmlAttribute("id")]
public int OrderID { get; set; }
}
[Serializable]
public class OrderMerchant
{
[XmlElement("merchant")]
public string Name { get; set; }
[XmlAttribute("id")]
public int ID { get; set; }
}
My problem: When I deserialize the XML and get an object, I have a Merchant object with an ID of 111 but a null Name. How do I mark up my object so that the element text is assigned to the Name attribute? I tried using the element name and I've tried an XPath expression (but I don't even know if that's allowed in this context).
You're telling the serializer to serialize an element merchant, and then the merchant object expects to receive another element "merchant" that will contain the name. Instead, mark the Name property with the attribute [XmlText] like so:
[Serializable]
public class OrderMerchant
{
[XmlText]
public string Name { get; set; }
[XmlAttribute("id")]
public int ID { get; set; }
}
And that should do it
Source

Deserializing list of different objects

Let's say, I have the the following C# classes
[JsonObject(MemberSerialization.OptIn)]
public class Parent
{
[JsonProperty]
public int SharedProp { get; set; }
}
public class ChildA : Parent
{
[JsonProperty]
public string ChildAProperty { get; set; }
}
public class ChildB : Parent
{
[JsonProperty]
public string ChildAProperty { get; set; }
}
Now I created a List<Parent> to which holds zero to n objects. Serialization of the list works fine and gives me a valid JSON file which I can deserialize. The problem is, I am currently only getting List<Parent> back and there is no ChildA or ChildB object.
I am using the Newtonsoft JSON serializer/deserializer. Is there any way to achieve this or do I have to split it into separate files/lists?
You need to specify the TypeNameHandling in the JsonSerializerSettings. Take a look at this article for an example.

Using Datacontract: WCF

How should i be declaring the datacontracts
My Operation contract has a Method:
Apple GetApples()
My data Contract Apple looks Like
[DataContract]
public class Apple
{
[DataMember]
public int Id { get; set; }
[DataMember]
public FruitType type { get; set; }
}
As there is another member of type FruitType.
[DataContract]
public class FruitType
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string type { get; set; }
}
OR
as a simple class
public class FruitType
{
public int Id { get; set; }
public string type { get; set; }
}
What is the difference between these two? other than that the simple type is not a datacontract and will depende on how i want to use it.?
how should i declare it??
Those attributes give you the control over how your properties will be represented in different formats. For example for XML you can specify the XML Namespace and XML node names.
Even if you are happy with default property names and default namespace, when you try to serialize data to XML, your XML nodes will have weird names such as typek_BackingField.
In other words, if you use WCF you should use DataContract and DataMember attributes, even if you think it works fine the formatted data may not look what you expect. As a result it removes compatibility with other (non-WCF) systems. Or even when you don't share your types (contracts) with other WCF systems.

Set Json Attribute on existing class

I have an existing class in an external assembly which I can't change.
I would like to serialize an object from this class with Newtonsoft JSON.Net, but not all the properties.
Normally I can do this with the JsonIgnoreAttribute attribute like this:
public class TestJsonClass
{
public string PropA { get; set; }
[JsonIgnoreAttribute]
public string PropB { get; set; }
}
But since I can't change the class, is there a way to ignore a property without attributes?
Try inherit class and override property with appropriate annotations or copy property values in a completely new class.

Categories