15

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?

1
  • How is the name ProductDTO present when an instance is serialized to JSON? JSON is untyped after all, and when I try to serialize an instance with JSON.NET, the class name isn't present. Commented Feb 13, 2013 at 11:11

2 Answers 2

18

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.

Sign up to request clarification or add additional context in comments.

1 Comment

About "class name into JSON-serialized data": you are right, JSON doesn't outputs the class name, this is just for XML.
3

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.