Reputation: 11721
I have a Data Transfer Object class for a product
public class ProductDTO
{
public Guid Id { get; set; }
public string Name { get; set; }
// Other properties
}
When the Asp.net serializes the object in JSON (using JSON.NET
) or in XML
, it generates ProductDTO
objects.
However, i want to change the name during serialization, from ProductDTO
to Product
, using some kind of attributes:
[Name("Product")]
public class ProductDTO
{
[Name("ProductId")]
public Guid Id { get; set; }
public string Name { get; set; }
// Other properties
}
How can i do this?
Upvotes: 15
Views: 12313
Reputation: 67987
I can't see why the class name should make it into the JSON-serialized data, but as regards XML you should be able to control the type name via DataContractAttribute, specifically via the Name property:
using System.Runtime.Serialization;
[DataContract(Name = "Product")]
public class ProductDTO
{
[DataMember(Name="ProductId")]
public Guid Id { get; set; }
[DataMember]
public string Name { get; set; }
// Other properties
}
DataContractAttribute is relevant because the default XML serializer with ASP.NET Web API is DataContractSerializer. DataContractSerializer is configured through DataContractAttribute applied to serialized classes and DataMemberAttribute applied to serialized class members.
Upvotes: 18
Reputation: 3271
An option is to use the default .Net Serialization attributes for this:
[DataContract(Name = "Product")]
public class ProductDTO
{
[DataMember(Name = "ProductId")]
public Guid Id { get; set; }
[DataMember]
public string Name { get; set; }
// Other properties
}
Upvotes: 3