Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net Web API: change class name when serializing

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?

like image 408
Catalin Avatar asked Feb 13 '13 10:02

Catalin


People also ask

When we decorate the class with the DataContract attribute When this attribute is present the class is serialized as follows?

If you need more control over the serialization, you can decorate the class with the DataContract attribute. When this attribute is present, the class is serialized as follows: "Opt in" approach: Properties and fields are not serialized by default.

What is serialization in Web API?

The Web API serializes all the public properties into JSON. In the older versions of Web API, the default serialization property was in PascalCase. When we are working with . NET based applications, the casing doesn't matter.

Is it right that ASP Net Web API has replaced WCF?

No, it's not true that ASP.NET Web API has replaced WCF. WCF was generally developed to develop SOAP-based services. ASP.NET Web API is a new way to develop non-SOAP-based services such as XML, JSON, etc.


1 Answers

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.

like image 107
aknuds1 Avatar answered Sep 29 '22 13:09

aknuds1