I have a Json data returning from service which contains field like Line# and others
I am creating Model class which will have property names same as the these filed. I will map the Json data and model class since the field name are same it will automatically map the values.
problem what i am facing is i cannot declare property name as Line# [against coding guidelines gives error]
Is there any alternative way for this?
If you're using Json.NET (and if you're not, you should probably look into it), you can specify the serialized member name with the JsonProperty attribute:
[JsonProperty("Line#")]
public int LineNumber { get; set; }
If you're using the built-in DataContractJsonSerializer, specify the name in the DataMember attribute:
[DataMember(Name = "Line#")]
public int LineNumber { get; set; }
Related
I have a class that has the following property
[BsonId]
public Guid EventId { get; private set; }
I would like to serialize(and deserialize) the class that has this property to MongoDB with the use of the ToBsonDocument method. Though through the use of the default serializer the resulting BSON type for the _id field is
"_id" : BinDate(3, "wX9ZnP0ApEWF0d5aXLgiUA==")
I would like it to be stored as a BsonString. I plan to create a custom SerializerBase<> extension class in the future to properly deserialize the string back to a Guid I just have not gotten there yet.
I know that I could simply change my property to be a String
[BsonId]
public String EventId { get; private set; }
But I would like to keep it as a Guid. I think to solve my problem I need to make use of a serialization tag but I am not sure which one, any ideas?
Actually I somehow managed to find my answer right after I posted this question.
By making use of the tag BsonRepresentation I can specify the BSON data type that I would like MongoDB to use when serializing the data.
[BsonRepresentation(BsonType.String)]
I have a domain model component with several entity classes. In another component i have entity repositories implemented using Json.NET serialization. I want to ignore some of the entity properties during serialization, so the straight forward solution would be to decorate those properties with the JsonIgnore attribute. However, out of principle, i would like to avoid references to other components - including 3rd party libraries like Json.NET - in my domain model.
I know that I can create a custom contract resolver as described here but it is hard to generalize what to serialize and what not to serialize in the various entities. Generally I want to ignore all readonly properties, but there are exceptions as for example collections:
public List<Pixel> Pixels
{
get { return this.Pixels; }
}
I can also create a dedicated contract resolver for each entity as described here but that seems like a high-maintenance solution to me - especially with numerous entities.
The ideal solution would be if Json.NET had support for some attribute within the .NET framework, but I cannot even find an appropriate candidate...
I thought about making my own custom Ignore attribute in my domain model and making a custom contract resolver that uses reflection to detect this attribute and ignores the decorated properties when serializing. But is that really the best solution to the given problem?
I believe by default that Json.net Respects the DataContractAttribute. Although you have to be inclusive instead of exclusive, it also means that the serialization can change to Microsofts Binary (or maybe xml) and not have to redesign your domain models.
If a class has many properties and you only want to serialize a small subset of them then adding JsonIgnore to all the others will be tedious and error prone. The way to tackle this scenario is to add the DataContractAttribute to the class and DataMemberAttributes to the properties to serialize. This is opt-in serialization, only the properties you mark up with be serialized, compared to opt-out serialization using JsonIgnoreAttribute.
[DataContract]
public class Computer
{
// included in JSON
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal SalePrice { get; set; }
// ignored
public string Manufacture { get; set; }
public int StockCount { get; set; }
public decimal WholeSalePrice { get; set; }
public DateTime NextShipmentDate { get; set; }
}
The Json serializer also supports opt-in serialization:
[JsonObject(MemberSerialization.OptIn)]
public class File
{
// excluded from serialization
// does not have JsonPropertyAttribute
public Guid Id { get; set; }
[JsonProperty]
public string Name { get; set; }
[JsonProperty]
public int Size { get; set; }
}
From the Optin enum value docs:
Only members marked with JsonPropertyAttribute or DataMemberAttribute are serialized. This member serialization mode can also be set by marking the class with DataContractAttribute.
You might consider using something like a View Model to control which properties of your entity model are serialized. I haven't used it myself, but looked into using it for a project of mine, but AutoMapper might be something to look into to decouple the entity model from your serialized model.
I need to deserialize some JavaScript object represented in JSON to an appropriate C# class. Given the nice features of automatic properties, I would prefer having them in these classes as opposed to just having fields. Unfortunately, the .NET serialization engine (at least, by default) totally ignores automatic properties on deserialization and only cares about the backing field, which is obviously not present in the JavaScript object.
Given that there's no standard way to name backing fields and to be honest I don't even want to bother with the "let's create a JavaScript object that looks like it had C# backing fields" approach as it sounds a bit dirty, the only way I could serialize JavaScript fields to C# auto-properties if I could force the serialization engine to somehow ignore the backing field and use the property directly. Unfortunately, I can't figure out how this is done or if this can be done at all. Any ideas would be appreciated.
EDIT: Here's an example:
Javascript:
function Cat()
{
this.Name = "Whiskers";
this.Breed = "Tabby";
}
var cat = new Cat();
This is then serialized to "{Name: 'Whiskers'}".
The C# class:
[Serializable()]
public class Cat
{
public string Name { get; set; }
public string Breed { get; set; }
}
And the deserialization code, that fails:
new DataContractJsonSerializer(typeof(Cat)).ReadObject(inputStream);
And it is apparent from the exception that it fails because it is looking for the backing field.
EDIT2: Here's the exception, if that helps (no inner exceptions):
System.Runtime.Serialization.SerializationException
"The data contract type 'Test.Cat'
cannot be deserialized because the
required data members
'<Name>k__BackingField, <Breed>k__BackingField' were not
found."
What's happening here is the deserializer is trying to guess the name of your backing fields.
You can solve this by adding explicit mappings (DataContract/DataMember attributes) like this:
[DataContract]
public class Cat
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Breed { get; set; }
}
You can do this with JavaScriptSerializer found in the System.Web.Script.Serialization namespace:
JavaScriptSerializer serializer = new JavaScriptSerializer();
Cat c = serializer.Deserialize<Cat>(jsonString);
I have POCO objects with automatic properties and this works just fine.
EDIT: I wrote about JSON Serializers in .NET which compares this serializer with DataContractJsonSerializer.
baretta's answer solved the k__BackingField bloat for me. Just a tiny addendum that you can decorate this class to auto serialize into either XML or JSON in a similar way:
[Serializable, XmlRoot, DataContract]
public class Cat
{
[XmlElement]
[DataMember]
public string Name { get; set; }
[XmlElement]
[DataMember]
public string Breed { get; set; }
}
... and then use a DataContractJsonSerializer or XmlSerializer to prepare it for your endpoint.
I'm assuming you are passing data via a web service. If you are using the WebService class with the ScriptMethod attribute uncommented-out, the web service methods can read JSON natively. They even use the same JavaScriptSerializer that was mentioned above. If you are using WCF I'm a little more fuzzy on the logic.
But make sure your JSON object are returning data for EVERY property in your class. In your error, there is mention of a Breed property that is not in your example.
Also, on the JavaScript side, do to the dynamic nature of JavaScript it is easy to add new properties to your objects. This can sometimes lead to circular references. You should remove any extra data that you might have added (just as you are sending data via the web method, then add it again once you are done).
I would like to know if there is a maneer (may be with data annotation) to set the value of
property.DisplayPropertyName
.
Do you have any idea please?!!
Actually I think you mean to ask how you can choose a different property as the display property (i.e., the property that is used to briefly denote objects of your class in the UI).
The Entity Framework Service that generates the metadata for scaffolding choose the first property of string type (as far as I know), but you can change that by applying the DisplayColumn attribute to your class:
[DisplayColumn("Alias")]
public class Person {
public string Name { get; set; }
public string Alias { get; set; }
}
Note, however, that this only works for properties that are actually mapped to a column in the database. (I was trying to use a computed property, not mapped, but that led to an error message while scaffolding.)
That is quite easy to do:
[DisplayName("RenamedProperty")]
you can even add a description
[Description("Demonstrates DisplayNameAttribute.")]
or perhaps you would like it to reference your resources so it adapts itself to the selected language:
[Display(Name = "Description", ResourceType = typeof(Resources))]
I haven't found any information on this, maybe someone could help.
I have an XML (simplified for convenience):
<content>
<field1>value</field1>
<field2>
<field3>value</field3>
</field2>
</content>
I try to deserialize it using such classes:
[XmlRoot("content")]
public class Content
{
[XmlElement]
public List<Item> Fields { get; set; }
}
public class Item
{
[XmlElement]
public List<Item> Fields { get; set; }
[XmlText]
public String Value { get; set; }
}
I have two questions:
Can I get the actual name of the field? Like [XmlName] string name; in the Item class? Or some kind of an attribute for the class itself? It is not possible to set the node name to "field" and add "type" attribute, for some reasons ;-) While the actual class and serialization process is really complicated, I'd prefer not to implement my own serializer.
Can I add a wildcard like [XmlElement("field*")]? I can't test it until I know the answer to the first question, so if there is a better option, I'd love to know it as well.
Thanks.
You can set the name of the matching XMl- Element or Attribute in the Constructor of the Attribute
[XmlAttribute("FieldAsAttribute")]
--> Will Serialize / Deserialize the Property to the Xml Attribute FieldAsAttribute
or
[XmlElement("FieldAsElement")]
--> Will Serialize / Deserialize the Property to the Xml Element FieldAsElement
The only answer here is that it's, unfortunately, not possible.
As a result we have written our own serialization routine.