简体   繁体   中英

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?

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM